<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Mobile extends CI_Controller {

	/**
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 * 		http://example.com/index.php/welcome
	 *	- or -  
	 * 		http://example.com/index.php/welcome/index
	 *	- or -
	 * Since this controller is set as the default controller in 
	 * config/routes.php, it's displayed at http://example.com/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/welcome/<method_name>
	 * @see http://codeigniter.com/user_guide/general/urls.html
	 */

	 //error code normal -> misal json 100
	 //error code keyword salah -> 200
	 //item ada ga valid -> 300

	public function index()
	{
		//$arr = array("user_id" => 2, "items" => array("123","111","111135"), "keyword" => "fsdfdfsfsdfw3");
		//$data = json_encode($arr);<br />
        
		$this->load->model('Mobile_model');
		
		//echo count($this->Mobile_model->get_journeyagenttoday('88002450'));

		//echo $this->Mobile_model->get_itemgroupbyiccid("89620951012000433204");
		//echo $this->Mobile_model->get_max_attempt();
		//$this->Mobile_model->add_sellin_detail('1','1');
		
		//$dataray = json_decode('["paket enduro"]',TRUE);
		//echo count($dataray);
		//echo $this->Mobile_model->add_outlet('sfa4',36,'dsdf  dsd hh ','wer nn wre','sdfs','0','0',"file/outlet/","Voucher","34534");
				
		
		//$this->Mobile_model->add_channel_program('12121','1','sfa4');
		//$data['item_name'] = $this->Mobile_model->get_item(1);
		//echo $this->Mobile_model->check_valid_item("89620951012000432909",'89348914');
		//$this->Mobile_model->get_kpi('89348914');
		//$this->load->view('welcome_message');
	}
	
	public function claimvalidateoutlet()
	{
		$this->load->model('Mobile_model');

		$dataray = array("user_id" => $this->input->post('user_id'), "keyword" => $this->input->post('keyword'), "channel_id" => $this->input->post('channel_id'));


		if(count($dataray) == 0)
		{
			$result = array("success" => "false", "error_code" => "100", "message" => "json format send failed");
			echo json_encode($result);
			exit;
		}

		$hasilkeyword = $this->Mobile_model->get_keywordtoday($dataray['user_id'],$dataray['keyword']);

		if(count($hasilkeyword) == 0)
		{
			$result = array("success" => "false", "error_code" => "200", "message" => "keyword failed", "user_id" => $dataray['user_id']);
			echo json_encode($result);
			exit;
		}

			$channel_id = "";
			$channel_name = "";
			$channel_address = "";
			$listarrayfrontliner=array();
			
		$outlets = $this->Mobile_model->get_outlet($dataray['channel_id']);
		
						if(count($outlets) == 0)
						{
							$result = array("success" => "false", "error_code" => "100", "message" => "Channel tidak ditemukan", "user_id" => $dataray['user_id']);
							echo json_encode($result);
							exit;
						}
						
						
						foreach($outlets as $outlet1)
						{
							
							//$listarrayoutlet = array("channel_id" => $dataray['channel_id'], "channel_name" => $outlet1['outlet_name'], "channel_address" => $outlet1['address']);
							$channel_id = $dataray['channel_id'];
							$channel_name = $outlet1['outlet_name'];
							$channel_address = $outlet1['address'];
						}
		$x=0;
		$fronts = $this->Mobile_model->get_outlet_frontliner($dataray['channel_id']);
						if(count($fronts) > 0)
						foreach($fronts as $front)
						{
							
							$listarrayfrontliner[$x] = array("frontliner_code" => $front['outlet_frontliner_id'] , "frontliner_name" => $front['frontliner_name']);
							$x++;
						}
		$result = array("success" => "true", "channel_id" => $channel_id, "channel_name" => $channel_name, "channel_address" => $channel_address, "frontliner_data" => $listarrayfrontliner);
			echo json_encode($result);
			
		
			
	}
	
	public function claimvalidateagent()
	{
		$this->load->model('Mobile_model');

		$dataray = array("user_id" => $this->input->post('user_id'), "keyword" => $this->input->post('keyword'), "channel_id" => $this->input->post('channel_id'));


		if(count($dataray) == 0)
		{
			$result = array("success" => "false", "error_code" => "100", "message" => "json format send failed");
			echo json_encode($result);
			exit;
		}

		$hasilkeyword = $this->Mobile_model->get_keywordtoday($dataray['user_id'],$dataray['keyword']);

		if(count($hasilkeyword) == 0)
		{
			$result = array("success" => "false", "error_code" => "200", "message" => "keyword failed", "user_id" => $dataray['user_id']);
			echo json_encode($result);
			exit;
		}

		$channel_id = "";
		$channel_name = "";
		$channel_address = "";

		$outlets = $this->Mobile_model->get_agent($dataray['channel_id']);
		
						if(count($outlets) == 0)
						{
							$result = array("success" => "false", "error_code" => "100", "message" => "Channel tidak ditemukan", "user_id" => $dataray['user_id']);
							echo json_encode($result);
							exit;
						}
						
						
						foreach($outlets as $outlet1)
						{
							
							//$listarrayoutlet = array("channel_id" => $dataray['channel_id'], "channel_name" => $outlet1['outlet_name'], "channel_address" => $outlet1['address']);
							$channel_id = $dataray['channel_id'];
							$channel_name = $outlet1['agent_name'];
							$channel_address = $outlet1['agent_address'];
						}
		
		$result = array("success" => "true", "channel_id" => $channel_id, "channel_name" => $channel_name, "channel_address" => $channel_address);
			echo json_encode($result);
			exit;
		
			
	}
	
	public function addclaim()
	{
		$this->load->model('Mobile_model');

		$data = file_get_contents("php://input");
		
		$dataray = json_decode($data,TRUE);

		if(count($dataray) == 0)
		{
			$result = array("success" => "false", "error_code" => "100", "message" => "json format send failed");
			echo json_encode($result);
			exit;
		}

		$hasilkeyword = $this->Mobile_model->get_keywordtoday($dataray['user_id'],$dataray['keyword']);

		if(count($hasilkeyword) == 0)
		{
			$result = array("success" => "false", "error_code" => "200", "message" => "keyword failed", "user_id" => $dataray['user_id']);
			echo json_encode($result);
			exit;
		}

		foreach($hasilkeyword as $clients)
			$client = $clients['client'];

		$matchs = array();
		$intcek = 0;
		
		$barangok = 0;
			$barangbad = 0;
			$valid_item = array();
			$failed_item = array();
			$failed_item_message = array();
			$good_item = array();
		
		if(count($dataray['items']) > 0)
		{	
		
			
		foreach($dataray['items'] as $dataitem)
			{
				//$matchs[$intcek] = array("true" => "valid", "value" => $dataitem);
				//$intcek++;
				$valid = "0";
				$valid = $this->Mobile_model->check_valid_item_warranty($dataitem,$dataray['user_id'],$dataray['channel_id']);
			
				//if(count($valids) > 0)
				//{
					//foreach($valids as $validku)
					//{
						//$valid = $validku['f_check_valid_item'];
						
						if($valid=="OK")
						{
								$good_item[$barangok] = $dataitem;
								$barangok++;
								$valid="0";
						}else{
						
							$failed_item_message[$barangbad] = $valid;
							$failed_item[$barangbad] = $dataitem;
							$barangbad++;
						}
					//}
				//}*/
				
			}
			
           
			if($barangbad == count($dataray['items']))
			{
				$result = array("success" => "false", "error_code" => "300", "message" => "Semua item tidak valid", "failed_items" => $failed_item, "failed_items_msg" => $failed_item_message , "user_id" => $dataray['user_id']);
				echo json_encode($result);
				exit;
			}
			else
			{
				$terrid = $this->Mobile_model->get_territory($dataray['channel_id']);
                

                
				//-----------------------start
				$this->db->trans_begin();
				//-----------------------begin process

				$claimid = $this->Mobile_model->add_claim($dataray,$terrid,$client);
                $this->mglobal->saveLog('add-claim-header',"added:".json_encode($dataray),$dataray['user_id'],'mobile-android',$dataray['user_id']);

				foreach($good_item as $perbaris)
				{
					$this->Mobile_model->add_claim_detail($perbaris,$claimid);
				}
				//-----------------------end process
				if ($this->db->trans_status() === FALSE)
				{
					$this->db->trans_rollback();
				}
				else
				{
					$this->db->trans_commit();
				}
				//-----------------------end
				if($barangok == count($dataray['items']))
				{
					$result = array("success" => "true", "failed_items" => $failed_item, "failed_items_msg" => $failed_item_message, "user_id" => $dataray['user_id']);
					echo json_encode($result);
					exit;
				}
				else
				{
					$result = array("success" => "true", "error_code" => "300", "message" => "Beberapa item tidak valid", "failed_items" => $failed_item, "failed_items_msg" => $failed_item_message, "user_id" => $dataray['user_id']);
					echo json_encode($result);
					exit;
				}
			}
		}

	}
	
	public function addScanIn()
	{
	   

       
		$this->load->model('Mobile_model');

		$data = file_get_contents("php://input");
		
		$dataray = json_decode($data,TRUE);

        
		if(count($dataray) == 0)
		{
			$result = array("success" => "false", "error_code" => "100", "message" => "json format send failed");
			echo json_encode($result);
			exit;
		}

		$hasilkeyword = $this->Mobile_model->get_keywordtoday($dataray['user_id'],$dataray['keyword']);

		if(count($hasilkeyword) == 0)
		{
			$result = array("success" => "false", "error_code" => "200", "message" => "keyword failed", "user_id" => $dataray['user_id']);
			echo json_encode($result);
			exit;
		}

		foreach($hasilkeyword as $clients)
			$client = $clients['client'];

		
        
        $matchs = array();
		$intcek = 0;
		
		$barangok = 0;
			$barangbad = 0;
			$valid_item = array();
			$failed_item = array();
			$failed_item_message = array();
			$good_item = array();
			
		$allow = $this->Mobile_model->check_allowscanin($dataray['user_id']);
		
		if($allow=="f")
		{
			$result = array("success" => "false", "error_code" => "100", "message" => "Scan in tidak diperbolehkan, hubungi admin", "user_id" => $dataray['user_id']);
			echo json_encode($result);
			exit;		
		}
		
        

            
		$creditlimit = $this->Mobile_model->getCreditLimit($dataray['user_id']);
		$currentlimit = $this->Mobile_model->getCurrentLimit($dataray['user_id']);
		
		

        
        if(count($dataray['items']) > 0)
		{	foreach($dataray['items'] as $dataitem)
			{
				//$matchs[$intcek] = array("true" => "valid", "value" => $dataitem);
				//$intcek++;
				$valid = "0";

				$valid = $this->Mobile_model->check_valid_item($dataitem,$dataray['user_id']);
			
				//if(count($valids) > 0)
				//{
					//foreach($valids as $validku)
					//{
						//$valid = $validku['f_check_valid_item'];
		
						if($valid=="1")
						{
							$query = $this->Mobile_model->get_itemdetail($dataitem);
							
							$hargaitem = $this->Mobile_model->get_price($dataitem,$dataray['user_id']);
							
							$currentlimit+=$hargaitem;
							
							if($currentlimit>=$creditlimit)
							{
								$failed_item_message[$barangbad] = "Limit tidak cukup";
								$failed_item[$barangbad] = $dataitem;
								$barangbad++;
								
							}else{
							$this->Mobile_model->update_item($dataitem,2);
							
							if(count($query) > 0)
							foreach($query as $hasilperbaris)
							{
								$groupid = $this->Mobile_model->get_itemgroupbyiccid($dataitem);
								$good_item[$barangok] = $dataitem;
								$valid_item[$barangok] = array("item_id" => $hasilperbaris['item_id'], "item_name" => $hasilperbaris['item_name'], "item_code" => $hasilperbaris['iccid'], "price" => $hargaitem, "item_group_id" => $groupid);
								$barangok++;
								
								
					
							}
							}
						$valid="0";
						}else{
						
							$failed_item_message[$barangbad] = $this->Mobile_model->check_valid_item_error_code($valid);
							$failed_item[$barangbad] = $dataitem;
							$barangbad++;
						}
					//}
				//}*/
				
			}
			/*
			$cluster = "";
			$clusters = $this->Mobile_model->get_cluster($dataray['user_id']);
			
			if(count($clusters) > 0)
			{
				foreach($clusters as $clusterku)
				{
					$cluster = $clusterku['f_get_cluster'];
				}
			}


			//$filteritems = $this->Mobile_model->get_itemsfromarray($matchs,$cluster);
			//var_dump($filteritems);
			//$hasilarray = $this->Mobile_model->get_iccidscaninfromarray($filteritems);
			//var_dump($hasilarray);
			
			$hasilarray = $this->Mobile_model->get_itemsfromarray($matchs,$cluster);
			
			
			foreach($hasilarray as $listbarang)
			{
				if($listbarang['true'] == "valid")
				{
					$this->Mobile_model->update_item($listbarang['value'],2);
				}
			}
			
			$barangok = 0;
			$barangbad = 0;
			$valid_item = array();
			$failed_item = array();
			$good_item = array();
			foreach($hasilarray as $listbarang)
			{
				if($listbarang['true'] == "valid")
				{
					$good_item[$barangok] = $listbarang['value'];
					$valid_item[$barangok] = $listbarang['detail'];
					$barangok++;
				}
				else
				{
					
					$failed_item[$barangbad] = $listbarang['value'];
					$barangbad++;
				}
			}
			*/
            

            
            
            
            
            
            
            
			if($barangbad == count($dataray['items']))
			{
				$result = array("success" => "false", "error_code" => "300", "message" => "Semua item tidak valid", "failed_items" => $failed_item, "failed_items_msg" => $failed_item_message , "user_id" => $dataray['user_id']);
				echo json_encode($result);
				exit;
			}
			else
			{
				//-----------------------start
				$this->db->trans_begin();
				//-----------------------begin process
				$scanid = $this->Mobile_model->add_scanin($dataray,$barangok,$client);
            $this->mglobal->saveLog('add-scanin-header',"added:".json_encode($dataray),$dataray['user_id'],'mobile-android',$dataray['user_id']);

				foreach($good_item as $perbaris)
				{
					$this->Mobile_model->add_scanin_detail($perbaris,$scanid);
				}
				
				//-----------------------end process
				if ($this->db->trans_status() === FALSE)
				{
					$this->db->trans_rollback();
				}
				else
				{
					$this->db->trans_commit();
				}
				//-----------------------end
				if($barangok == count($dataray['items']))
				{
					$result = array("success" => "true", "user_id" => $dataray['user_id'], "failed_items" => $failed_item, "failed_items_msg" => $failed_item_message, "valid_items" => $valid_item);
					echo json_encode($result);
					exit;
				}
				else
				{
					$result = array("success" => "true", "error_code" => "300", "message" => "Beberapa item tidak valid", "failed_items" => $failed_item, "failed_items_msg" => $failed_item_message, "user_id" => $dataray['user_id'], "valid_items" => $valid_item);
					echo json_encode($result);
					exit;
				}
			}
		}

	}
	public function addeload()
	{
	$this->load->model('Mobile_model');

		$data = file_get_contents("php://input");
		
		$dataray = json_decode($data,TRUE);
		
		if(count($dataray) == 0)
		{
			$result = array("success" => "false", "error_code" => "100", "message" => "json format send failed");
			echo json_encode($result);
			exit;
		}

		$hasilkeyword = $this->Mobile_model->get_keywordtoday($dataray['user_id'],$dataray['keyword']);

		if(count($hasilkeyword) == 0)
		{
			$result = array("success" => "false", "error_code" => "200", "message" => "keyword failed", "user_id" => $dataray['user_id']);
			echo json_encode($result);
			exit;
		}
		
		$hasilarray = $this->Mobile_model->get_eloadnumber($dataray['channel_id']);
		
		$eloadnumber="";
		if(count($hasilarray) > 0)
		{
			foreach($hasilarray as $parseresult)
			{
			$eloadnumber=$parseresult['eload_number'];
					
			}
		}

		if($eloadnumber!="")
		{
		
			//-----------------------start
			$this->db->trans_begin();
			//-----------------------begin process

			$this->Mobile_model->add_eload($dataray['user_id'],$dataray['channel_id'],$eloadnumber,$dataray['eload_value'],$dataray['date']);
			
            //-----------------------end process
            

				if ($this->db->trans_status() === FALSE)
				{
					$this->db->trans_rollback();
				}
				else
				{
					$this->db->trans_commit();
     $this->mglobal->saveLog('add-eload',"added:".json_encode($dataray),$dataray['user_id'],'mobile-android',$dataray['user_id']);

				}
				//-----------------------end
				
			$result = array("success" => "true", "user_id" => $dataray['user_id']);
					echo json_encode($result);
					exit;
		}else{
		$result = array("success" => "false", "error_code" => "100", "message" => "Nomor e-load tidak terdaftar");
			echo json_encode($result);
			exit;
		}
		


	
	}

	public function addeloadagent()
	{
	$this->load->model('Mobile_model');

		$data = file_get_contents("php://input");
		
		$dataray = json_decode($data,TRUE);
		
		if(count($dataray) == 0)
		{
			$result = array("success" => "false", "error_code" => "100", "message" => "json format send failed");
			echo json_encode($result);
			exit;
		}

		$hasilkeyword = $this->Mobile_model->get_keywordtoday($dataray['user_id'],$dataray['keyword']);

		if(count($hasilkeyword) == 0)
		{
			$result = array("success" => "false", "error_code" => "200", "message" => "keyword failed", "user_id" => $dataray['user_id']);
			echo json_encode($result);
			exit;
		}
		
		$hasilarray = $this->Mobile_model->get_agent_eloadnumber($dataray['channel_id']);
		
		$eloadnumber="";
		if(count($hasilarray) > 0)
		{
			foreach($hasilarray as $parseresult)
			{
			$eloadnumber=$parseresult['agent_mdn_evo'];
					
			}
		}
		
		if($eloadnumber!="")
		{
			//-----------------------start
				$this->db->trans_begin();
				//-----------------------begin process
			$this->Mobile_model->add_eload($dataray['user_id'],$dataray['channel_id'],$eloadnumber,$dataray['eload_value'],$dataray['date']);
			//-----------------------end process
				if ($this->db->trans_status() === FALSE)
				{
					$this->db->trans_rollback();
				}
				else
				{
					$this->db->trans_commit();
                $this->mglobal->saveLog('add-eload',"added:".json_encode($dataray),$dataray['user_id'],'mobile-android',$dataray['user_id']);

				}
				//-----------------------end

			$result = array("success" => "true", "user_id" => $dataray['user_id']);
					echo json_encode($result);
					exit;
		}else{
		$result = array("success" => "false", "error_code" => "100", "message" => "Nomor e-load tidak terdaftar");
			echo json_encode($result);
			exit;
		}
		
		

	
	}
	
	/**
	 * Untuk menyimpan sebuah transaksi sell in, kita validasi dulu datanya dan urutannya adalah sbb:
	 * + Apakah ada data yang dikirim? 
	 * + Apakah item (ICCID) yang akan disimpan valid belum pernah disell in atau posisi bukan di konsinyasi
	 */
	public function addSellIn() {
		$this->load->model('Mobile_model');
		$data = file_get_contents("php://input");
		$dataray = json_decode($data, TRUE);     

		if($dataray['top_id'] == "" OR $dataray['top_id'] == null)
			{ $dataray['top_id'] = '1'; }

		#1
		if(count($dataray) == 0) {
			$result = array("success" => "false", "error_code" => "100", "message" => "Forat data rusak");
			echo json_encode($result);
			exit;
		}
		
		#? 
		$keyword = $this->Mobile_model->get_keywordtoday($dataray['user_id'], $dataray['keyword']);
		if(count($keyword) == 0) {
			$result = array("success" => "false", "error_code" => "200", "message" => "Keyword Gagal", "user_id" => $dataray['user_id']);
			echo json_encode($result);
			exit;
		}

		#?
		if ($dataray['channel_id'] == '' OR is_null($dataray['channel_id'])) {   
			$result = array("success" => "false", "error_code" => "300", "message" => "Partner Id Tidak Terbaca", "user_id" => $dataray['user_id']);
			echo json_encode($result);
			exit;
		}

		#2#ValidateItem
		$validated_iccid = $this->Mobile_model->ValidateItem($dataray["items"]);
		// var_dump($validated_iccid);
		if(count($validated_iccid['invalid']) != 0 && count($validated_iccid['valid']) != 0 ) {
			$invalid_iccid = "\n\r";
			foreach ($validated_iccid['invalid'] as $key) {
				$invalid_iccid .= $key.", ";
			}
			$invalid_iccid = substr($invalid_iccid, 0, -6); 
			$result = array("success" => "false", "error_code" => "100", "message" => "ICCID tidak valid: $invalid_iccid ", "user_id" => $dataray['user_id']);
		}
		if(count($validated_iccid['valid']) == 0) {
			$result = array("success" => "false", "error_code" => "100", "message" => "Semua item tidak sudah pernah dijual atau konsinyasi", "user_id" => $dataray['user_id']);
			echo json_encode($result);
		}
		else { // start the save_trans sequence
			$this->db->trans_begin();
				$trx_id = $this->Mobile_model->add_sellin($dataray);
				if(count($dataray['program_ho']) == 0 )
					{ $program_id[] = 1; }
				else
					{ $program_id[] = $dataray['program_ho'][0]; }
				if($program_id[0] == 'null' OR $program_id[0] == '' )
					{ $program_id[0] = '1'; }
				if($dataray['program_cluster'])
					{ $program_id[] = $dataray['program_cluster'][0]; }
				foreach($program_id as $programitem)
					{ $this->Mobile_model->add_sellin_program($trx_id, $programitem, $dataray['user_id']); }

				$this->Mobile_model->add_sellin_detail($validated_iccid['valid'], $trx_id, $dataray['user_id']);
				foreach ($dataray["items"] as $key) {
					$this->Mobile_model->update_scanin($key, 2, $trx_id, "Sell In");
				}

				$db_sri = $this->load->database('Retails', TRUE);
				$db_sri->trans_begin();
				$this->load->model('mintegrasi');
				$this->mintegrasi->StockIn($dataray["channel_id"], $validated_iccid['valid'], $trx_id, 'sell_in', $dataray['user_id']);
				$this->mglobal->saveLog( 'sell_in', 'create; id='. json_encode(array('sell_in_id' => $trx_id, 'partner_id' => $dataray['channel_id'], 'iccid' => $validated_iccid['valid'], 'sell_in_program_id' => $program_id) ), $dataray['user_id'], 'mobile-android' );

			if ($this->db->trans_status() === FALSE OR $db_sri->trans_status() === FALSE) { 
			  $this->db->trans_rollback();
				$db_sri->trans_rollback();
				$result = array("success" => "false", "error_code" => "100", "message" => "Transaksi gagal", "user_id" => $dataray['user_id']);
				echo json_encode($result);
			}
			else { 
				$this->db->trans_commit();
				$db_sri->trans_commit();
				$result = array("success" => "true", "message" => "Transaksi sukses", "user_id" => $dataray['user_id']);
				echo json_encode($result);
			}
		}
	} // end of add_sellin()

	public function updateJourney()
	{
		$this->load->model('Mobile_model');
		
		$data = file_get_contents("php://input");
		
		$dataray = json_decode($data,TRUE);

		if(count($dataray) == 0)
		{
			$result = array("success" => "false", "error_code" => "100", "message" => "json format send failed");
			echo json_encode($result);
			exit;
		}

		$hasilkeyword = $this->Mobile_model->get_keywordtoday($dataray['user_id'],$dataray['keyword']);

		if(count($hasilkeyword) == 0)
		{
			$result = array("success" => "false", "error_code" => "200", "message" => "keyword failed", "user_id" => $dataray['user_id']);
			echo json_encode($result);
			exit;
		}

		$hasilarray = $this->Mobile_model->get_user_by_id($dataray['user_id']);
		foreach($hasilarray as $user)
		{
            //Edited By RAA
            //Dont need to check anymore
			//if($user['user_group_id']==31)
			$datajc = $this->Mobile_model->get_journey($user['user_group_id'],$dataray['jc_id']);
			//else
			//$datajc = $this->Mobile_model->get_journey($dataray['user_id'],$dataray['jc_id']);
		}
		

		foreach($datajc as $datajc1)
		{
		//if($user['user_group_id']==31){
					$datajc1['channel_id']=$this->Mobile_model->get_channel_id_by_territory_id($datajc1['territory_id']);
		//	}
	
						//-----------------------start
				$this->db->trans_begin();
				//-----------------------begin process
            //Patched by Raa : Check In insert to track
            //check param lat
            if(isset($dataray['latitude']) and $dataray['latitude']!='0' and $dataray['latitude']!='0.0'){
                $lat=$dataray['latitude'];
            } else {
                $lat=NULL;
            }
            //check param lon
            if(isset($dataray['longitude']) and $dataray['latitude']!='0' and $dataray['latitude']!='0.0'){
                $lon=$dataray['longitude'];
            } else {
                $lon=NULL;
            }
            //add_journey ditambah parameter lat lon
            $parring='';
            if(isset($dataray['parring_id'])){
            $parring=$dataray['parring_id'];
            }
            $via='';
            $remark='';
            if(isset($dataray['via'])){
                $via=$dataray['via'];
            }
            if(isset($dataray['remark'])){
                $remark=$dataray['remark'];
            }
            
            
			$this->Mobile_model->add_journey($dataray['user_id'],$dataray['check_in_date'],$dataray['route_date'],$datajc1['channel_id'],$dataray['jc_id'],$lat,$lon,$dataray['acc'],$dataray['type'],$parring,$via,$remark);
			//-----------------------end process
				if ($this->db->trans_status() === FALSE)
				{
					$this->db->trans_rollback();
				}
				else
				{
					$this->db->trans_commit();
				}
				//-----------------------end

		}
       $this->mglobal->saveLog('update-journey',"added:".json_encode($dataray),$dataray['user_id'],'mobile-android',$dataray['user_id']);

		$result = array("success" => "true", "user_id" => $dataray['user_id']);
		echo json_encode($result);
	}

	public function addSellReturn()
	{
		$this->load->model('Mobile_model');
		
		$data = file_get_contents("php://input");
		
		$dataray = json_decode($data,TRUE);
		
		if(count($dataray) == 0)
		{
			$result = array("success" => "false", "error_code" => "100", "message" => "json format send failed");
			echo json_encode($result);
			exit;
		}

		$hasilkeyword = $this->Mobile_model->get_keywordtoday($dataray['user_id'],$dataray['keyword']);

		if(count($hasilkeyword) == 0)
		{
			$result = array("success" => "false", "error_code" => "200", "message" => "keyword failed", "user_id" => $dataray['user_id']);
			echo json_encode($result);
			exit;
		}

		foreach($hasilkeyword as $clients)
			$client = $clients['client'];

		$matchs = array();
		$intcek = 0;
		if(count($dataray['items']) > 0)
		{	foreach($dataray['items'] as $dataitem)
			{
				$matchs[$intcek] = array("true" => "valid", "value" => $dataitem);
				$intcek++;
			}

			$hasilarray = $this->Mobile_model->get_iccidsellreturnfromarray($matchs);

			$barangok = 0;
			$barangbad = 0;
			$failed_item = array();
			$good_item = array();
			foreach($hasilarray as $listbarang)
			{
				if($listbarang['true'] == "valid")
				{
					$good_item[$barangok] = $listbarang['value'];
					$barangok++;
				}
				else
				{
					
					$failed_item[$barangbad] = $listbarang['value'];
					$barangbad++;
				}
			}

			if($barangbad == count($hasilarray))
			{
				$result = array("success" => "false", "error_code" => "300", "message" => "All item code are not valid", "failed_items" => $failed_item, "user_id" => $dataray['user_id']);
				echo json_encode($result);
				exit;
			}
			else
			{
			//-----------------------start
				$this->db->trans_begin();
				//-----------------------begin process
				$returnid = $this->Mobile_model->add_sellreturn($dataray,$client);

				foreach($good_item as $perbaris)
				{
					$this->Mobile_model->add_sellreturn_detail($perbaris,$returnid);
				}
				//-----------------------end process
				if ($this->db->trans_status() === FALSE)
				{
					$this->db->trans_rollback();
				}
				else
				{
					$this->db->trans_commit();
                    $this->mglobal->saveLog('add-sell-return-header',"added:".json_encode($dataray),$dataray['user_id'],'mobile-android',$dataray['user_id']);

				}
				//-----------------------end
				if($barangok == count($hasilarray))
				{
					$result = array("success" => "true", "failed_items" => $failed_item, "user_id" => $dataray['user_id']);
					echo json_encode($result);
					exit;
				}
				else
				{
					$result = array("success" => "true", "error_code" => "300", "message" => "Some item are not valid", "failed_items" => $failed_item, "user_id" => $dataray['user_id']);
					echo json_encode($result);
					exit;
				}

			}
		}
		
	}
    
	public function addStockScan()
	{
		$this->load->model('Mobile_model');
		
		$data = file_get_contents("php://input");
		
		$dataray = json_decode($data,TRUE);

		if(count($dataray) == 0)
		{
			$result = array("success" => "false", "error_code" => "100", "message" => "json format send failed");
			echo json_encode($result);
			exit;
		}

		$hasilkeyword = $this->Mobile_model->get_keywordtoday($dataray['user_id'],$dataray['keyword']);

		if(count($hasilkeyword) == 0)
		{
			$result = array("success" => "false", "error_code" => "200", "message" => "keyword failed", "user_id" => $dataray['user_id']);
			echo json_encode($result);
			exit;
		}
		
		$matchs = array();
		$intcek = 0;
		if(count($dataray['items']) > 0)
		{	foreach($dataray['items'] as $dataitem)
			{
				$matchs[$intcek] = array("true" => "valid", "value" => $dataitem);
				$intcek++;
			}

			$hasilarray = $this->Mobile_model->get_iccidstockscanfromarray($matchs);

			$barangok = 0;
			$barangbad = 0;
			$failed_item = array();
			$good_item = array();
			foreach($hasilarray as $listbarang)
			{
				if($listbarang['true'] == "valid")
				{
					$good_item[$barangok] = $listbarang['value'];
					$barangok++;
				}
				else
				{			
					$failed_item[$barangbad] = $listbarang['value'];
					$barangbad++;
				}
			}

			if($barangbad == count($hasilarray))
			{
				$result = array("success" => "false", "error_code" => "300", "message" => "All item code are not valid", "failed_items" => $failed_item, "user_id" => $dataray['user_id']);
				echo json_encode($result);
				exit;
			}
			else
			{
			//-----------------------start
				$this->db->trans_begin();
				//-----------------------begin process
				$scanid = $this->Mobile_model->add_stockscan($dataray,$barangok);

				foreach($good_item as $perbaris)
				{
					$this->Mobile_model->add_stockscan_detail($perbaris,$scanid);
				}
				//-----------------------end process
				if ($this->db->trans_status() === FALSE)
				{
					$this->db->trans_rollback();
				}
				else
				{
					$this->db->trans_commit();
                    $this->mglobal->saveLog('add-stock-scan',"added:".json_encode($dataray),$dataray['user_id'],'mobile-android',$dataray['user_id']);

				}
				//-----------------------end
				
				if($barangok == count($hasilarray))
				{
					$result = array("success" => "true", "failed_items" => $failed_item, "user_id" => $dataray['user_id']);
					echo json_encode($result);
					exit;
				}
				else
				{
					$result = array("success" => "true", "error_code" => "300", "message" => "Some item are not valid", "failed_items" => $failed_item, "user_id" => $dataray['user_id']);
					echo json_encode($result);
					exit;
				}

			}
		}
	}

	public function trackUser()
	{
		$this->load->model('Mobile_model');

		$longitude = $this->input->get('lon');
		$latitude = $this->input->get('lat');
		$user_id = $this->input->get('user_id');
		$cell_id = $this->input->get('cell_id');
         $lac = $this->input->get('lac');
		//-----------------------start
				$this->db->trans_begin();
				//-----------------------begin process
        
        if($lac == "" or $lac==null){
            $this->Mobile_model->add_trackuser($longitude,$latitude,$user_id,$cell_id);
        }else{
            $this->Mobile_model->add_trackuser($longitude,$latitude,$user_id,$cell_id,$lac);
        }
		
		
				//-----------------------end process
				if ($this->db->trans_status() === FALSE)
				{
					$this->db->trans_rollback();
				}
				else
				{
					$this->db->trans_commit();
				}
				//-----------------------end
	}
	
	public function getitemgroup() 
	{
		$this->load->model('Mobile_model');

		$hasilarray = $this->Mobile_model->get_itemgroup();

		if(is_null($hasilarray))
		{
			$result = array("success" => "false", "error_code" => "100", "message" => "Data is empty");
			echo json_encode($result);
		}
		else
		{
			$result['success'] = "true";
			$ins = 0;
			foreach($hasilarray as $perbaris)
			{
				$result['item_groups'][$ins] = array("item_group_id" => $perbaris['item_group_name'], "item_group_name" => $perbaris['item_group_name']);
				$ins++;
			}
			echo json_encode($result);
		}
	}

	public function prodCatalog()
	{
		$this->load->model('Mobile_model');

		$hasilarray = $this->Mobile_model->get_prodcatalog();

		if(is_null($hasilarray))
		{
			$result = array("success" => "false", "error_code" => "100", "message" => "Data is empty");
			echo json_encode($result);
		}
		else
		{
			$result['success'] = "true";
			$ins = 0;
			foreach($hasilarray as $perbaris)
			{
				$result['items'][$ins] = array("item_id" => $perbaris['item_id'], "item_name" => $perbaris['item_name'], "item_code" => $perbaris['iccid'], "price" => $perbaris['default_price']);
				$ins++;
			}
			echo json_encode($result);
		}
	}

	public function prodCatalogbyitemgroup()
	{
		$this->load->model('Mobile_model');

		$data = file_get_contents("php://input");

		$dataray = json_decode($data,TRUE);

		if(count($dataray) == 0)
		{
			$result = array("success" => "false", "error_code" => "100", "message" => "json format send failed");
			echo json_encode($result);
			exit;
		}
		else
		{
			$userid = $dataray['user_id'];
			$keyword = $dataray['keyword'];
			$itemgroupid = $dataray['item_group_id'];
		}

		$hasilarray = $this->Mobile_model->get_prodcatalog2($itemgroupid);

		if(is_null($hasilarray))
		{
			$result = array("success" => "false", "error_code" => "100", "message" => "Data is empty");
			echo json_encode($result);
		}
		else
		{
			$result['success'] = "true";
			$result['user_id'] = $userid;
			$ins = 0;
			foreach($hasilarray as $perbaris)
			{
				$result['items'][$ins] = array("item_id" => $perbaris['item_id'], "item_name" => $perbaris['item_name'], "item_code" => $perbaris['iccid'], "price" => $perbaris['default_price']);
				$ins++;
			}
			echo json_encode($result);
		}
	}

	public function addmerchancapture()
	{
		$this->load->library('upload');
		$this->load->model('Mobile_model');

		if(!empty($_FILES['uploadedfile']['name']))
		{
			$config['upload_path'] = 'file/merchan/';
            $config['allowed_types'] = 'gif|jpg|png';
            //$config['max_size'] = '100';
            //$config['max_width']  = '1024';
            //$config['max_height']  = '768';  

			$this->upload->initialize($config);

			if ($this->upload->do_upload('uploadedfile'))
            {
				$userid = $this->input->post('user_id');
				$keyword = $this->input->post('keyword');
			
				$hasilkeyword = $this->Mobile_model->get_keywordtoday($userid,$keyword);

				if(count($hasilkeyword) == 0)
				{
					$result = array("success" => "false", "error_code" => "200", "message" => "keyword failed", "user_id" => $dataray['user_id']);
					echo json_encode($result);
					exit;
				}
				
				$tanggalku = $this->input->post('date');

                $dataray = array("user_id" => $this->input->post('user_id'), "channel_id" => $this->input->post('channel_id'), "lon" => $this->input->post('lon'), "lat" => $this->input->post('lat'), "link" => "file/merchan/".$_FILES['uploadedfile']['name'], "tanggal" => $tanggalku, "pic_type" => $this->input->post('pic_type'), "keyword" => $keyword);

				//-----------------------start
				$this->db->trans_begin();
				//-----------------------begin process
				$this->Mobile_model->add_merchancapture($dataray);

				//-----------------------end process
				if ($this->db->trans_status() === FALSE)
				{
					$this->db->trans_rollback();
				}
				else
				{
					$this->db->trans_commit();
                    $this->mglobal->saveLog('add-marchan-capture',"added:".json_encode(array($this->input->post('user_id'),$this->input->post('keyword'))),$this->input->post('user_id'),'mobile-android',$this->input->post('user_id'));
				}
				//-----------------------end
				$result = array("success" => "true", "user_id" => $this->input->post('user_id'));
				echo json_encode($result);

            }
			else
			{
				$result = array("success" => "false", "error_code" => "100", "message" => "Upload file failed", "user_id" => $this->input->post('user_id'));
				echo json_encode($result);
			}
		}
	}


	public function addmerchandiser()
	{
       
		$this->load->library('upload');
		$this->load->model('Mobile_model');

		if(!empty($_FILES['uploadedfile']['name']))
		{
			$config['upload_path'] = 'file/merchandiser/';
            $config['allowed_types'] = 'gif|jpg|png';
            //$config['max_size'] = '100';
            //$config['max_width']  = '1024';
            //$config['max_height']  = '768';  

			$this->upload->initialize($config);

			if ($this->upload->do_upload('uploadedfile'))
            {
				$userid = $this->input->post('user_id');
				$keyword = $this->input->post('keyword');
			
				$hasilkeyword = $this->Mobile_model->get_keywordtoday($userid,$keyword);

				if(count($hasilkeyword) == 0)
				{
					$result = array("success" => "false", "error_code" => "200", "message" => "keyword failed", "user_id" => $dataray['user_id']);
					echo json_encode($result);
					exit;
				}
				
				$tanggalku = $this->input->post('date');

                $dataray = array("user_id" => $this->input->post('user_id'), "channel_id" => $this->input->post('channel_id'), "lon" => $this->input->post('lon'), "lat" => $this->input->post('lat'), "link" => "file/merchandiser/".$_FILES['uploadedfile']['name'], "tanggal" => $tanggalku, "pic_type" => $this->input->post('pic_type'), "keyword" => $keyword);

				//-----------------------start
				$this->db->trans_begin();
				//-----------------------begin process
                

                if($dataray['pic_type']=='visit'){
				$this->Mobile_model->add_merchandiser($dataray);
                $this->mglobal->saveLog('add-merchandiser',"added:".json_encode(array($userid)),$userid,'mobile-android',$userid);
                }else{
                  
                  
                  
                  
                  
                  
                  
                    //echo "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb";
                    $jpg=explode(":",$dataray['pic_type']);
                    if (count($jpg)>0){
                        $merchandiserid=$this->Mobile_model->get_merchandiserheader($jpg[0]);
                        if($merchandiserid!=null){
                        $datadetail=array("merchandiser_id"=>$merchandiserid,"pic_type"=>$jpg[1],"img"=>$dataray['link']);
                        $this->Mobile_model->add_merchandiser_detail($datadetail);
                        }else{//header tidak ditemukan
                        $result = array("success" => "false", "error_code" => "100", "message" => "Foto Visit Belum Di Upload/Tidak Ditemukan", "user_id" => $this->input->post('user_id'));
				        echo json_encode($result);
                        exit;
                        }
                    }else{//pictype tidak dikenal
                        $result = array("success" => "false", "error_code" => "100", "message" => "Foto Tipe Tidak Valid", "user_id" => $this->input->post('user_id'));
				        echo json_encode($result);
                        exit;
                    }
                }


				//-----------------------end process
                
                
				if ($this->db->trans_status() === FALSE)
				{
					$this->db->trans_rollback();
				}
				else
				{
					$this->db->trans_commit();
				}
				//-----------------------end
				$result = array("success" => "true", "user_id" => $this->input->post('user_id'));
				echo json_encode($result);

            }
			else
			{
				$result = array("success" => "false", "error_code" => "100", "message" => "Upload file failed", "user_id" => $this->input->post('user_id'));
				echo json_encode($result);
			}
		}
	}
    
    
    
    
	public function addagent()
	{
		$this->load->library('upload');
		$this->load->model('Mobile_model');

		$userid = $this->input->post('user_id');
		$keyword = $this->input->post('keyword');
		//$agentid = $this->input->post('agent_id');
		$agentname = $this->input->post('agent_name');
		$agentaddress = $this->input->post('agent_address');
		$agentcity = $this->input->post('agent_city');
		$agentbf = $this->input->post('agent_business_focus');
		$agenttype = $this->input->post('agent_type');
		$agentstype = $this->input->post('agent_selling_type');
		$longitude = $this->input->post('longitude');
		$latitude = $this->input->post('latitude');
		$eloadnumber = $this->input->post('eload_number');
		
		$program = $this->input->post('program_ho');
		
		
		
		$programaray = json_decode($program,TRUE);
		
		$programc = $this->input->post('program_cluster');
		
		$programarayc = json_decode($programc,TRUE);
		
		
		$hasilkeyword = $this->Mobile_model->get_keywordtoday($userid,$keyword);

		if(count($hasilkeyword) == 0)
		{
			$result = array("success" => "false", "error_code" => "200", "message" => "keyword failed", "user_id" => $userid);
			echo json_encode($result);
			exit;
		}

		if(!empty($_FILES['agent_foto']['name']))
		{
			$config['upload_path'] = 'file/agent/';
            $config['allowed_types'] = 'gif|jpg|png';
            //$config['max_size'] = '100';
            //$config['max_width']  = '1024';
            //$config['max_height']  = '768';  

			$this->upload->initialize($config);

			if ($this->upload->do_upload('agent_foto'))
            {
			
				
				$territoryid = $this->Mobile_model->get_cluster($userid);

		//$territoryidlast = $this->Mobile_model->add_territorymtr($agentname,$territoryid,$userid,6);
		//$this->Mobile_model->add_territorymtruser($userid,$territoryidlast);
		//-----------------------start
				$this->db->trans_begin();
				//-----------------------begin process
		$agentid=$this->Mobile_model->add_agent($userid,$territoryid,$agentname,$agentaddress,$agentcity,$agentbf,$agentstype,$longitude,$latitude,$eloadnumber,"file/agent/".$_FILES['agent_foto']['name'],$agenttype);
				
				$this->Mobile_model->delete_channel_program($agentid);
				if(count($programaray)>0)
				foreach($programaray as $programitem)
				{
					$this->Mobile_model->add_channel_program($agentid,$programitem,$userid);
				}
				
				if(count($programarayc)>0)
				foreach($programarayc as $programitem)
				{
					$this->Mobile_model->add_channel_program($agentid,$programitem,$userid);
				}
				//-----------------------end process
				if ($this->db->trans_status() === FALSE)
				{
					$this->db->trans_rollback();
				}
				else
				{
					$this->db->trans_commit();
                    $this->mglobal->saveLog('add-agent',"added:".json_encode(array($userid,$territoryid)),$userid,'mobile-android',$userid);
				}
				//-----------------------end
            }
			else
			{
				$result = array("success" => "false", "error_code" => "100", "message" => "Upload file failed", "user_id" => $this->input->post('user_id'));
				echo json_encode($result);
				exit;
			}
		}
		else
		{
		$result = array("success" => "false", "error_code" => "100", "message" => "Upload file failed", "user_id" => $this->input->post('user_id'));
				echo json_encode($result);
				exit;
			
		}

		$result = array("success" => "true", "user_id" => $userid);
		echo json_encode($result);
		/*$this->load->model('Mobile_model');

		$data = file_get_contents("php://input");

		$dataray = json_decode($data,TRUE);

		if(count($dataray) == 0)
		{
			$result = array("success" => "false", "error_code" => "100", "message" => "json format send failed");
			echo json_encode($result);
			exit;
		}
		else
		{
			$userid = $dataray['user_id'];
			$keyword = $dataray['keyword'];
			$agentid = $dataray['agent_id'];
			$agentname = $dataray['agent_name'];
			$agentaddress = $dataray['agent_address'];
			$agentcity = $dataray['agent_city'];
			$agentbf = $dataray['agent_business_focus'];
			$agenttype = $dataray['agent_type'];
			$longitude = $dataray['longitude'];
			$latitude = $dataray['latitude'];
			$programho = $dataray['program_ho'];
			$programcluster = $dataray['program_cluster'];
		}

		$hasilkeyword = $this->Mobile_model->get_keywordtoday($dataray['user_id'],$dataray['keyword']);

		if(count($hasilkeyword) == 0)
		{
			$result = array("success" => "false", "error_code" => "200", "message" => "keyword failed", "user_id" => $dataray['user_id']);
			echo json_encode($result);
			exit;
		}

		
		
		
		$territoryid = $this->Mobile_model->get_cluster($userid);

		$territoryidlast = $this->Mobile_model->add_territorymtr($agentname,$territoryid,$userid,6);
		$this->Mobile_model->add_territorymtruser($userid,$territoryidlast);
		$this->Mobile_model->add_agent($userid,$agentid,$territoryidlast,$agentname,$agentaddress,$agentcity,$agentbf,$agenttype,$longitude,$latitude);

		$this->Mobile_model->delete_channel_program($agentid);
		
		if(count($programho)>0)
				foreach($programho as $programitem)
				{
					$this->Mobile_model->add_channel_program($agentid,$programitem,$userid);
				}
				
				if(count($programcluster)>0)
				foreach($programcluster as $programitem)
				{
					$this->Mobile_model->add_channel_program($agentid,$programitem,$userid);
				}
				
		$result = array("success" => "true", "user_id" => $userid);
		echo json_encode($result);*/
		
		
	}

	public function addoutlet()
	{
		$this->load->library('upload');
		$this->load->model('Mobile_model');

		$userid = $this->input->post('user_id');
		$keyword = $this->input->post('keyword');
		$outletname = $this->input->post('outlet_name');
		$outletaddress = $this->input->post('outlet_address');
		$outletcity = $this->input->post('outlet_city');
		$outletbf = $this->input->post('outlet_business_focus');
		$longitude = $this->input->post('longitude');
		$latitude = $this->input->post('latitude');
		$eloadnumber = $this->input->post('eload_number');
		
		$program = $this->input->post('program_ho');
		
		$programaray = json_decode($program,TRUE);
		
		$programc = $this->input->post('program_cluster');
		
		$programarayc = json_decode($programc,TRUE);
		
		
		$hasilkeyword = $this->Mobile_model->get_keywordtoday($userid,$keyword);

		if(count($hasilkeyword) == 0)
		{
			$result = array("success" => "false", "error_code" => "200", "message" => "keyword failed", "user_id" => $userid);
			echo json_encode($result);
			exit;
		}

		if(!empty($_FILES['outlet_foto']['name']))
		{
			$config['upload_path'] = 'file/outlet/';
            $config['allowed_types'] = 'gif|jpg|png';
            //$config['max_size'] = '100';
            //$config['max_width']  = '1024';
            //$config['max_height']  = '768';  

			$this->upload->initialize($config);

			if ($this->upload->do_upload('outlet_foto'))
            {
				/*$reportsz = $this->Mobile_model->get_reportto($userid);
				
				$reportid = "";
				if(count($reportsz) > 0)
				{
					foreach($reportsz as $reports)
						$reportid = $reports['reporting_to'];

					if($reportid == "")
					{
						$result = array("success" => "false", "error_code" => "100", "message" => "Reporting_to not found", "user_id" => $userid);
						echo json_encode($result);
						exit;
					}
				}

				$territories = $this->Mobile_model->get_territorybyuserid($reportid,3);

				$territoryid = 0;
				if(count($territories) > 0)
				{
					foreach($territories as $territoriesx)
						$territoryid = $territoriesx['territory_id'];

					if($territoryid == 0)
					{
						$result = array("success" => "false", "error_code" => "100", "message" => "Territory_id not found", "user_id" => $userid);
						echo json_encode($result);
						exit;
					}
				}*/

				//$territoryidlast = $this->Mobile_model->add_territorymtr($outletname,$territoryid,$userid,5);
				//$this->Mobile_model->add_territorymtruser($userid,$territoryidlast);
				
				$territoryid = $this->Mobile_model->get_cluster($userid);
				//-----------------------start
				$this->db->trans_begin();
				//-----------------------begin process
				$outletid=$this->Mobile_model->add_outlet($userid,$territoryid,$outletname,$outletaddress,$outletcity,$longitude,$latitude,"file/outlet/".$_FILES['outlet_foto']['name'],$outletbf,$eloadnumber);
				//$this->Mobile_model->add_outletdata($outletidlast,$outletbf);
				
				//$this->Mobile_model->add_channel_program('1231','1',$userid);
				$this->Mobile_model->delete_channel_program($outletid);
				if(count($programaray)>0)
				foreach($programaray as $programitem)
				{
					$this->Mobile_model->add_channel_program($outletid,$programitem,$userid);
				}
				
				if(count($programarayc)>0)
				foreach($programarayc as $programitem)
				{
					$this->Mobile_model->add_channel_program($outletid,$programitem,$userid);
				}
				//-----------------------end process
				if ($this->db->trans_status() === FALSE)
				{
					$this->db->trans_rollback();
				}
				else
				{
					$this->db->trans_commit();
                    $this->mglobal->saveLog('add-outlet',"added:".json_encode(array($userid,$outletid)),$userid,'mobile-android',$userid);
				}
				//-----------------------end
            }
			else
			{
				$result = array("success" => "false", "error_code" => "100", "message" => "Upload file failed", "user_id" => $this->input->post('user_id'));
				echo json_encode($result);
				exit;
			}
		}
		else
		{
		$result = array("success" => "false", "error_code" => "100", "message" => "Upload file failed", "user_id" => $this->input->post('user_id'));
				echo json_encode($result);
				exit;
			/*	$reportsz = $this->Mobile_model->get_reportto($userid);
				
				$reportid = "";
				if(count($reportsz) > 0)
				{
					foreach($reportsz as $reports)
						$reportid = $reports['reporting_to'];

					if($reportid == "")
					{
						$result = array("success" => "false", "error_code" => "100", "message" => "Reporting_to not found", "user_id" => $userid);
						echo json_encode($result);
						exit;
					}
				}

				$territories = $this->Mobile_model->get_territorybyuserid($reportid,3);

				$territoryid = 0;
				if(count($territories) > 0)
				{
					foreach($territories as $territoriesx)
						$territoryid = $territoriesx['territory_id'];

					if($territoryid == 0)
					{
						$result = array("success" => "false", "error_code" => "100", "message" => "Territory_id not found", "user_id" => $userid);
						echo json_encode($result);
						exit;
					}
				}

				$territoryidlast = $this->Mobile_model->add_territorymtr($outletname,$territoryid,$userid,5);
				$this->Mobile_model->add_territorymtruser($userid,$territoryidlast);
				$outletidlast = $this->Mobile_model->add_outlet($territoryidlast,$outletname,$outletaddress,$outletcity,$longitude,$latitude,"");
				$this->Mobile_model->add_outletdata($outletidlast,$outletbf);*/
		}

		$result = array("success" => "true", "user_id" => $userid);
		echo json_encode($result);
	}

	public function updateoutlet()
	{
	   
       

            
		$this->load->model('Mobile_model');

		$data = file_get_contents("php://input");

		$dataray = json_decode($data,TRUE);

		if(count($dataray) == 0)
		{
			$result = array("success" => "false", "error_code" => "100", "message" => "json format send failed");
			echo json_encode($result);
			exit;
		}
		else
		{
			$outletid = $dataray['outlet_id'];
			$outletname = $dataray['outlet_name'];
			$outletaddress = $dataray['outlet_address'];
			$outletcity = $dataray['outlet_city'];
			$outletbf = $dataray['outlet_business_focus'];
			$eloadnumber = $dataray['eload_number'];
			$programho = $dataray['program_ho'];
			$programcluster = $dataray['program_cluster'];
			
		}

		$hasilkeyword = $this->Mobile_model->get_keywordtoday($dataray['user_id'],$dataray['keyword']);

		if(count($hasilkeyword) == 0)
		{
			$result = array("success" => "false", "error_code" => "200", "message" => "keyword failed", "user_id" => $dataray['user_id']);
			echo json_encode($result);
			exit;
		}


		$territoryid = $this->Mobile_model->get_cluster($dataray['user_id']);
		//-----------------------start

				$this->db->trans_begin();
				//-----------------------begin process

		$a=$this->Mobile_model->update_outlet($outletid,$territoryid,$dataray['user_id'],$outletname,$outletaddress,$outletcity,$outletbf,$eloadnumber);
		//$this->Mobile_model->update_outletdata($outletid,$outletbf);

		$this->Mobile_model->delete_channel_program($outletid);

		if(count($programho)>0)
				foreach($programho as $programitem)
				{
					$this->Mobile_model->add_channel_program($outletid,$programitem,$dataray['user_id']);
				}
				
				if(count($programcluster)>0)
				foreach($programcluster as $programitem)
				{
					$this->Mobile_model->add_channel_program($outletid,$programitem,$dataray['user_id']);
				}
		//-----------------------end process
				if ($this->db->trans_status() === FALSE)
				{
					$this->db->trans_rollback();
				}
				else
				{
					$this->db->trans_commit();
                    $this->mglobal->saveLog('update-outlet',"added:".json_encode($dataray),$dataray['user_id'],'mobile-android',$dataray['user_id']);
				}
				//-----------------------end

		$result = array("success" => "true", "user_id" => $dataray['user_id']);
		echo json_encode($result);
	}

	public function updateagent()
	{
		$this->load->model('Mobile_model');

		$data = file_get_contents("php://input");

		$dataray = json_decode($data,TRUE);

		if(count($dataray) == 0)
		{
			$result = array("success" => "false", "error_code" => "100", "message" => "json format send failed");
			echo json_encode($result);
			exit;
		}
		else
		{
			$agentid = $dataray['agent_id'];
			$agentname = $dataray['agent_name'];
			$agentaddress = $dataray['agent_address'];
			$agentcity = $dataray['agent_city'];
			$agentbf = $dataray['agent_business_focus'];
			$agenttype = $dataray['agent_type'];
			$eloadnumber = $dataray['eload_number'];
			$programho = $dataray['program_ho'];
			$programcluster = $dataray['program_cluster'];
			$agentstype = $dataray['agent_selling_type'];
		}

		$hasilkeyword = $this->Mobile_model->get_keywordtoday($dataray['user_id'],$dataray['keyword']);

		if(count($hasilkeyword) == 0)
		{
			$result = array("success" => "false", "error_code" => "200", "message" => "keyword failed", "user_id" => $dataray['user_id']);
			echo json_encode($result);
			exit;
		}

		$territoryid = $this->Mobile_model->get_cluster($dataray['user_id']);
		//-----------------------start
				$this->db->trans_begin();
				//-----------------------begin process
		$this->Mobile_model->update_agent($agentid,$territoryid,$dataray['user_id'],$agentname,$agentaddress,$agentcity,$agentbf,$agentstype,$eloadnumber,$agenttype);
		
		$this->Mobile_model->delete_channel_program($agentid);
		
		if(count($programho)>0)
				foreach($programho as $programitem)
				{
					$this->Mobile_model->add_channel_program($agentid,$programitem,$dataray['user_id']);
				}
				
				if(count($programcluster)>0)
				foreach($programcluster as $programitem)
				{
					$this->Mobile_model->add_channel_program($agentid,$programitem,$dataray['user_id']);
				}
			//-----------------------end process
				if ($this->db->trans_status() === FALSE)
				{
					$this->db->trans_rollback();
				}
				else
				{
					$this->db->trans_commit();
                    $this->mglobal->saveLog('update-agent',"added:".json_encode($dataray),$dataray['user_id'],'mobile-android',$dataray['user_id']);
				}
				//-----------------------end
		$result = array("success" => "true", "user_id" => $dataray['user_id']);
		echo json_encode($result);
	}

	public function getoutletbyuserid()
	{
		$this->load->model('Mobile_model');
		
		$data = file_get_contents("php://input");

		$dataray = json_decode($data,TRUE);

		if(count($dataray) == 0)
		{
			$result = array("success" => "false", "error_code" => "100", "message" => "json format send failed");
			echo json_encode($result);
			exit;
		}

		$hasilkeyword = $this->Mobile_model->get_keywordtoday($dataray['user_id'],$dataray['keyword']);

		if(count($hasilkeyword) == 0)
		{
			$result = array("success" => "false", "error_code" => "200", "message" => "keyword failed", "user_id" => $dataray['user_id']);
			echo json_encode($result);
			exit;
		}

		$dataterritory = $this->Mobile_model->get_territorybyuserid($dataray['user_id'],5);
		if(is_null($dataterritory))
		{
			$result = array("success" => "false", "error_code" => "100", "message" => "Data is empty");
			echo json_encode($result);
			exit;
		}

		$ins = 0;
		foreach($dataterritory as $territorys)
		{
			$hasilarray = $this->Mobile_model->get_outletbyterritoryid($territorys['territory_id']);

			$result['success'] = "true";
			$result['user_id'] = $dataray['user_id'];

			if(count($hasilarray) > 0)
			foreach($hasilarray as $perbaris)
			{
				$databisnis = $this->Mobile_model->get_bisnisfocusbyoutlet($perbaris['outlet_id']);
				
				$bisnisfocus1 = "";
				if(count($databisnis) > 0)
				foreach($databisnis as $bisnisfocus)
					$bisnisfocus1 = $bisnisfocus['outlet_business_focus'];
					
				$dataprogram = $this->Mobile_model->get_channel_program($perbaris['outlet_id']);
				
				$channelhoprogram = array();
				$channelclusterprogram = array();
				if(count($dataprogram) > 0)
				foreach($dataprogram as $program){
					$yyy=0;
					$detailprogram = $this->Mobile_model->get_program($program['program_id']);
				
				
					if(count($detailprogram) > 0)
					foreach($detailprogram as $detail){
						if($detail['territory_id']=="1")
							$channelhoprogram[$yyy]=$program['program_id'];
						else
							$channelclusterprogram[$yyy]=$program['program_id'];
						$yyy++;
					}
					
				}

				$result['outlets'][$ins] = array("outlet_id" => $perbaris['outlet_id'], "outlet_name" => $perbaris['outlet_name'], "outlet_address" => $perbaris['address'], "outlet_city" => $perbaris['city'], "outlet_business_focus" => $bisnisfocus1,"eload_number" => $perbaris['eload_number'],"program_ho" => $channelhoprogram,"program_cluster" => $channelclusterprogram);
				$ins++;
			}
		}
		echo json_encode($result);

	}

	public function getagentbyuserid()
	{
		$this->load->model('Mobile_model');
		
		$data = file_get_contents("php://input");

		$dataray = json_decode($data,TRUE);

		if(count($dataray) == 0)
		{
			$result = array("success" => "false", "error_code" => "100", "message" => "json format send failed");
			echo json_encode($result);
			exit;
		}

		$hasilkeyword = $this->Mobile_model->get_keywordtoday($dataray['user_id'],$dataray['keyword']);

		if(count($hasilkeyword) == 0)
		{
			$result = array("success" => "false", "error_code" => "200", "message" => "keyword failed", "user_id" => $dataray['user_id']);
			echo json_encode($result);
			exit;
		}

		$dataterritory = $this->Mobile_model->get_territorybyuserid($dataray['user_id'],6);
		if(is_null($dataterritory))
		{
			$result = array("success" => "false", "error_code" => "100", "message" => "Data is empty");
			echo json_encode($result);
			exit;
		}

		$ins = 0;
		foreach($dataterritory as $territorys)
		{
			$hasilarray = $this->Mobile_model->get_agentbyterritoryid($territorys['territory_id']);
			$result['success'] = "true";
			$result['user_id'] = $dataray['user_id'];
			if(count($hasilarray) > 0)
			foreach($hasilarray as $perbaris)
			{
			
			$dataprogram = $this->Mobile_model->get_channel_program($perbaris['agent_id']);
				
				$channelhoprogram = array();
				$channelclusterprogram = array();
				if(count($dataprogram) > 0)
				foreach($dataprogram as $program){
					$yyy=0;
					$detailprogram = $this->Mobile_model->get_program($program['program_id']);
				
				
					if(count($detailprogram) > 0)
					foreach($detailprogram as $detail){
						if($detail['territory_id']=="1")
							$channelhoprogram[$yyy]=$program['program_id'];
						else
							$channelclusterprogram[$yyy]=$program['program_id'];
						$yyy++;
					}
					
				}
				
				$result['agents'][$ins] = array("agent_id" => $perbaris['agent_id'], "agent_name" => $perbaris['agent_name'], "agent_address" => $perbaris['agent_address'], "agent_city" => $perbaris['agent_city'], "agent_business_focus" => $perbaris['agent_business_focus'], "agent_type" => $perbaris['agent_type'],"agent_selling_type" => $perbaris['agent_selling_type'],"program_ho" => $channelhoprogram,"program_cluster" => $channelclusterprogram, "eload_number" => $perbaris['agent_mdn_evo']);
				$ins++;
			}
		}
		echo json_encode($result);
	}

	public function addDynamicForm()
	{
		$this->load->model('Mobile_model');
		$this->load->library('upload');

		$namatabel = $this->input->post('tablename');
		$serviceid = $this->input->post('serviceid');

		$getfield = $this->Mobile_model->get_fieldnamefromproperty($serviceid);

		if(count($getfield))
		{
			$fieldku = "(";
			$valueku = "(";
			$kxx = 0;
			foreach($getfield as $fields)
			{
				if($fields['t_elm_type'] == "checkbox")
				{
					$masukan = "";

					$tempcount = 0;
					foreach($this->input->post($fields['t_services_column']) as $nilaic)
					{
						if($tempcount == 0)
							$masukan .= $nilaic;
						else
							$masukan .= "|".$nilaic;
						
						$tempcount++;
					}

					if($kxx == 0)
					{
						$fieldku .= $fields['t_services_column'];
						$valueku .= "'".$masukan."'";
					}
					else
					{
						$fieldku .= ",".$fields['t_services_column'];
						$valueku .= ",'".$masukan."'";
					}
				}
				elseif($fields['t_elm_type'] == "photo")
				{
					if(!empty($_FILES[$fields['t_services_column']]['name']))
					{
						$dir_path = "file/imagedf/".$namatabel."/";
						if(!is_dir($dir_path)){
							if (!mkdir($dir_path)) {
								die('Failed to create folders...');
							}
						}

						$config['upload_path'] = $dir_path;
						$config['allowed_types'] = 'gif|jpg|png';
            
						$this->upload->initialize($config);

						if ($this->upload->do_upload($fields['t_services_column']))
						{
							if($kxx == 0)
							{
								$fieldku .= $fields['t_services_column'];
								$valueku .= "'".$dir_path.$_FILES[$fields['t_services_column']]['name']."'";	
							}
							else
							{
								$fieldku .= ",".$fields['t_services_column'];
								$valueku .= ",'".$dir_path.$_FILES[$fields['t_services_column']]['name']."'";
							}
						}
						else
						{
							if($kxx == 0)
							{
								$fieldku .= $fields['t_services_column'];
								$valueku .= "''";
							}
							else
							{
								$fieldku .= ",".$fields['t_services_column'];
								$valueku .= ",''";
							}
						}
					}
				}
				else
				{
					if($kxx == 0)
					{
						$fieldku .= $fields['t_services_column'];
						$valueku .= "'".$this->input->post($fields['t_services_column'])."'";
					}
					else
					{
						$fieldku .= ",".$fields['t_services_column'];
						$valueku .= ",'".$this->input->post($fields['t_services_column'])."'";
					}
				}

				$kxx++;
			}

			$fieldku .= ")";
			$valueku .= ")";
			
			//-----------------------start
				$this->db->trans_begin();
				//-----------------------begin process
			$this->Mobile_model->add_formdinamik("insert into $namatabel $fieldku values $valueku");
			//-----------------------end process
				if ($this->db->trans_status() === FALSE)
				{
					$this->db->trans_rollback();
				}
				else
				{
					$this->db->trans_commit();
				}
				//-----------------------end
		}
		
		$result = array("success" => "true");
		echo json_encode($result);
	}

	public function getclosestgallery()
	{
		$this->load->model('Mobile_model');

		$userid = $this->input->get('user_id');
		$lat = $this->input->get('lat');
		$lon = $this->input->get('lon');
		
		$radius = 0.045;
		$lat_max = floatval($lat) + $radius;
		$lat_min = floatval($lat) - $radius;
		$lon_max = floatval($lon) + $radius;
		$lon_min = floatval($lon) - $radius;

		$galleries = $this->Mobile_model->get_closestgallery($userid,$lon_max,$lon_min,$lat_max,$lat_min);
		
		if(is_null($galleries))
		{
			$result = array("success" => "false", "error_code" => "100", "message" => "Data is empty");
			echo json_encode($result);
			exit;
		}

		$result['success'] = "true";
		$result['user_id'] = $userid;
		foreach($galleries as $galleryku)
		{
			$result['gallery'][$ins] = array("gallery_id" => $galleryku['gallery_id'], "gallery_name" => $galleryku['gallery_name'], "gallery_address" => $galleryku['gallery_address']);
			$ins++;
		}
		echo json_encode($result);
	}

	public function updatepassword()
	{
		$this->load->model('Mobile_model');
		
		$dataray = array("username" => $this->input->post('username'), "password" => $this->input->post('password'), "newpassword" => $this->input->post('newpassword'));

		
		if(count($dataray) == 0)
		{
			$result = array("success" => "false", "error_code" => "100", "message" => "json format send failed");
			echo json_encode($result);
			exit;
		}
		
		$hasilarray = $this->Mobile_model->get_user($dataray);

		if(count($hasilarray) == 0)
		{
			$result = array("success" => "false", "error_code" => "100", "message" => "User tidak ditemukan");
			echo json_encode($result);
			exit;
		}
		else
		{
		foreach($hasilarray as $hsl1)
		{
			if($hsl1['user_password'] != md5($dataray['password']))
				{
					
					$result = array("success" => "false", "error_code" => "100", "message" => "Password lama salah");
					echo json_encode($result);
					exit;
				}
				
				
			$min_password=$this->Mobile_model->get_min_password();
			
			if(strlen($dataray['newpassword'])<$min_password)
			{
				$result = array("success" => "false", "error_code" => "100", "message" => "Panjang password harus lebih dari ".$min_password);
					echo json_encode($result);
					exit;
			}
			
			$this->Mobile_model->update_user_password($hsl1['user_id'],$dataray['newpassword']);
			$this->Mobile_model->update_user_must_change_password($hsl1['user_id']);
            
            $this->mglobal->saveLog('update-user-password',"added:".json_encode($dataray),$hsl1['user_id'],'mobile-android',$hsl1['user_id']);
            
			$result = array("success" => "true", "user_id" => $hsl1['user_id']);
		echo json_encode($result);
		}
		
		}
		
		
	
	}
    
    //Enhanced By RAA
    //Function to capture logout into log
    public function logout($user_id,$timestamp=""){
        //modivied by donny        
		$this->load->model('Mobile_model');
        if ($timestamp!=""){
            $time=explode('_',$timestamp);
        } else {
           // $timestamp=now();
            $time[0]=date('d-m-Y');
            $time[1]=date('H:i:s');            
             $this->Mobile_model->updateLoginStatus($user_id,0);
        }
        
        
        $this->mglobal->saveLog('mobile-userlogout',"(logout at $time[0] $time[1])",$user_id,'mobile-android',$user_id);
    }
       
	public function login()
	{
		$this->load->helper('file');
		$this->load->model('Mobile_model');
		$this->load->library('Helpme');
        
		$dataray = array("username" => $this->input->post('username'), "password" => $this->input->post('password'), "imei" => $this->input->post('imei'), "imsi" => $this->input->post('imsi'), "v" => $this->input->post('v'));

		$hasilarray = $this->Mobile_model->get_user($dataray);
		$min_password=$this->Mobile_model->get_min_password();
		
		$appupdate = $this->Mobile_model->get_appupdate($dataray['username'],$dataray['v'],$this->input->post('client'));
        
		if(count($appupdate) > 0)
		{
			$urlupdate="";
			foreach($appupdate as $hsl1)
			{
				$urlupdate=$hsl1['app_path'];
			}
			
			$result = array("success" => "true", "update" => "true", "url" => $urlupdate);
            $this->mglobal->saveLog('mobile-update-app',$urlupdate,$this->input->post('username'),'mobile-android',$this->input->post('username'));
			echo json_encode($result);
			exit;
		}
		
		if(count($hasilarray) == 0)
		{
			$result = array("success" => "false", "error_code" => "100", "message" => "User tidak ditemukan");
            $this->mglobal->saveLog('mobile-userlogin','not found',$this->input->post('username'),'mobile-android',$this->input->post('username'));
			echo json_encode($result);
			exit;
		}
		else
		{
			
			foreach($hasilarray as $hsl1)
			{
				
				$must_change_password=$hsl1['must_change_password'];
				
				if($hsl1['user_password'] != md5($dataray['password']))
				{
					$this->Mobile_model->update_user($dataray['username'],$hsl1['logon_attempt']+1);
					
					$max_attempt=$this->Mobile_model->get_max_attempt();
				
					if($hsl1['logon_attempt'] >= $max_attempt)
					{
					
						$result = array("success" => "false", "error_code" => "100", "message" => "10 kesalahan atau lebih, kontak admin");
						$this->mglobal->saveLog('mobile-userlogin','max attemp',$this->input->post('username'),'mobile-android',$this->input->post('username'));
						echo json_encode($result);
						exit;
					}
					
					$result = array("success" => "false", "error_code" => "100", "message" => "Password salah");
					$this->mglobal->saveLog('mobile-userlogin','wrong password',$this->input->post('username'),'mobile-android',$this->input->post('username'));
					echo json_encode($result);
					exit;
				}
				
				
				
				if($hsl1['is_allowed_time'] == 0)
				{
					$result = array("success" => "false", "error_code" => "100", "message" => "Login tidak diperbolehkan");
                    $this->mglobal->saveLog('mobile-userlogin','not allowed',$this->input->post('username'),'mobile-android',$this->input->post('username'));
					echo json_encode($result);
					exit;
				}
				
				
			}
			
			$this->Mobile_model->update_user($dataray['username'],0);

			$imsi = $this->input->post('imsi');
			$imei = $this->input->post('imei');

			$cekhandset = $this->Mobile_model->cekhandset($hasilarray[0]['user_id'],$imsi,$imei);
			
			if(count($cekhandset) == 0)
			{
				$result = array("success" => "false", "error_code" => "100", "message" => "Invalid handset");
				$this->mglobal->saveLog('mobile-userlogin','invalid handset',$this->input->post('username'),'mobile-android',$this->input->post('username'));
				echo json_encode($result);
				exit;
			}
		}





		$client = $this->input->post('client');
		$setday="";
		$keyword = "";
		
		$tablelist = array();
		//$listarrayjourney = array();
		$listarrayevent = array();
		$parseresult = array();
		$listarrayclusteruser = array();
		$listarrayitemgroup = array();
		
		$listarrayho = array();

		$listarraycluster = array();
		
		$listarrayhouser = array();
		
		$listarraytop = array();
		$listarrayterm = array();
		
		if(count($hasilarray) > 0)
		{
			foreach($hasilarray as $parseresult)
			{
				$keywords = $this->Mobile_model->get_keyword($parseresult['user_id']);

				$randstring = "".mt_rand();
				
				if(count($keywords) > 0)
				{

					foreach($keywords as $keyword1)
					{
						
							//$this->Mobile_model->update_keyword1($parseresult['user_id'],$client);
							$keyword = $keyword1['keyword'];
						
					}
				}
				else
				{
					$this->Mobile_model->add_keyword($parseresult['user_id'],$randstring,$client);
					$keyword = $randstring;
				}
				
				$servicedetail = $this->Mobile_model->get_servicedetail($hasilarray[0]['user_group_id']);

				if(count($servicedetail) > 0)
				{
					$rowx = 0;

					foreach($servicedetail as $tableget)
					{
						//$getfield = $this->Mobile_model->get_fieldname($tableget['services_tabel']);
						$getfield = $this->Mobile_model->get_fieldnamefromproperty($tableget['services_id']);

						$ceki = 0;
						if(count($getfield))
						{
							$ceki ++;
							$isi = "";
							$datecek = 1;
							foreach($getfield as $fields)
							{
								if($fields['t_elm_type'] == "radio" || $fields['t_elm_type'] == "checkbox" || $fields['t_elm_type'] == "dropdown")
								{
									$isi .= $fields['t_elm_label']."<br>";
				
									$getsource = $this->Mobile_model->get_datasourcelink($fields['t_source_name'],$fields['t_source_column_display'],$fields['t_source_column_value']);

									if($fields['t_elm_type'] == "radio")
									{		
										if(count($getsource) > 0)
										{
											foreach($getsource as $detailsource)
											{
													$isi .= "<input type=radio name='".$fields['t_services_column']."' id='".$fields['t_services_column']."' value='".$detailsource['jjj1']."' /> ".$detailsource['jjj0']."<br/>";
											}
										}
									}
									elseif($fields['t_elm_type'] == "checkbox")
									{
										if(count($getsource) > 0)
										{
											foreach($getsource as $detailsource)
											{
													$isi .= "<input type=checkbox name='".$fields['t_services_column']."[]' id='".$fields['t_services_column']."[]' value='".$detailsource['jjj1']."' /> ".$detailsource['jjj0']."<br/>";
											}
										}
									}
									else
									{
										$isi .= "<select name='".$fields['t_services_column']."' id='".$fields['t_services_column']."' style='padding: 6px 10px; border-radius: 6px; -webkit-border-radius: 6px'>";
										if(count($getsource) > 0)
										{
											foreach($getsource as $detailsource)
											{
													$isi .= "<option value='".$detailsource['jjj1']."'> ".$detailsource['jjj0']."</option>";
											}
										}
										$isi .= "</select><br/>";
									}
								}
								elseif($fields['t_elm_type'] == "text")
									$isi .= $fields['t_elm_label']."<br/><input type=text name='".$fields['t_services_column']."' id='".$fields['t_services_column']."' style='padding: 6px 10px; border-radius: 6px; -webkit-border-radius: 6px'/><br/>";
								elseif($fields['t_elm_type'] == "textarea")
									$isi .= $fields['t_elm_label']."<br/><textarea name='".$fields['t_services_column']."' id='".$fields['t_services_column']."' cols='30' rows='5' style='padding: 6px 10px; border-radius: 6px; -webkit-border-radius: 6px'/></textarea><br/>";
								elseif($fields['t_elm_type'] == "gps")
									$isi .= "<a href=\"javascript:window.HTMLOUT.accessLocation('gps');\">".$fields['t_elm_label']."</a><input type='hidden' name='".$fields['t_services_column']."' id='gps'/><br/>";
								elseif($fields['t_elm_type'] == "photo")
									$isi .= "<a href=\"javascript:window.HTMLOUT.accessMedia('camera');\">".$fields['t_elm_label']."</a><input type='hidden' name='".$fields['t_services_column']."' id='img'/><br/>";
								elseif($fields['t_elm_type'] == "barcode")
									$isi .= "<a href=\"javascript:window.HTMLOUT.accessBarcode();\">".$fields['t_elm_label']."</a><input type='hidden' name='".$fields['t_services_column']."' id='barcode'/><br/>";
								elseif($fields['t_elm_type'] == "date")
								{
									$isi .= "<a href=\"javascript:window.HTMLOUT.accessDate('".$datecek."');\">".$fields['t_elm_label']."</a><input type='hidden' name='".$fields['t_services_column']."' id='date".$datacek."'/><br/>";
									$datecek++;
								}

							}

							$jsnya = "<script type=\"text/javascript\">
									function parseForm(event) {
										var form = this;
										if (this.tagName.toLowerCase() != 'form')
											form = this.form;    
										var data = '';
										if (!form.method)  form.method = 'get';
											data += 'method==' + form.method;
										data += '&&action==' + form.action;     
										/*	var inputs = document.forms[0].getElementsByTagName('input');
										for (var i = 0; i < inputs.length; i++) {
											var field = inputs[i];
											if (field.type != 'submit' && field.type != 'reset' && field.type != 'button')
												data += '&&' + field.name + '==' + field.value + '==' + field.getAttribute('id');
										} */
										var inputs = document.forms[0].getElementsByTagName('input');
										for (var i = 0; i < inputs.length; i++) {
											var field = inputs[i];
											if (field.type != 'submit' && field.type != 'reset' && field.type != 'button' && field.type != 'radio' && field.type != 'checkbox'){
												data += '&&' + field.name + '==' + field.value + '==' + field.getAttribute('id');
											}
											else if(field.type == 'radio')
											{
												if (field.checked) {
													data += '&&' + field.name + '==' + field.value + '==' + field.getAttribute('id');
												}
											}
											else if(field.type == 'checkbox')
											{
												if (field.checked) {
													data += '&&' + field.name + '==' + field.value + '==' + field.getAttribute('id');
												}
											}	         
										}
			   
										var inputs = document.forms[0].getElementsByTagName('select');
										for (var i = 0; i < inputs.length; i++) {
											var field = inputs[i];
											if (field.type != 'submit' && field.type != 'reset' && field.type != 'button')
												data += '&&' + field.name + '==' + field.value + '==' + field.getAttribute('id');
										}
										var inputs = document.forms[0].getElementsByTagName('textarea');
										for (var i = 0; i < inputs.length; i++) {
											var field = inputs[i];
											if (field.type != 'submit' && field.type != 'reset' && field.type != 'button')
												data += '&&' + field.name + '==' + field.value + '==' + field.getAttribute('id');
											}
										window.HTMLOUT.processFormData(data);
									}
	       
									for (var form_idx = 0; form_idx < document.forms.length; ++form_idx)
										document.forms[form_idx].addEventListener('submit', parseForm, false);   
									var inputs = document.getElementsByTagName('input');
									for (var i = 0; i < inputs.length; i++) {
										if (inputs[i].getAttribute('type') == 'button')
											inputs[i].addEventListener('click', parseForm, false);
									}
									</script>";

							$forms = "<html><body style=''><form method=post action='http://202.53.249.205/smartfren/index.php/mobile/adddynamicform'><input type=hidden name=serviceid value=".$tableget['services_id']."><input type=hidden name=tablename value=".$tableget['services_tabel'].">$isi<center><input type='button' value='kirim' style='border-radius: 6px; -webkit-border-radius: 6px; width: 98%'></center></form>".$jsnya."</html>";
							write_file("formgenerate/".$tableget['services_tabel'].".html",$forms);

							$tablelist[$rowx] = array("form_id" => $tableget['services_id'], "form_name" => "form/".$tableget['services_name'], "form_download_url" => "http://202.53.249.205/smartfren/formgenerate/".$tableget['services_tabel'].".html");
								
							$rowx++;
						}
					}
				}
			}

			$berita = "";

			$territoryids = $this->Mobile_model->get_parentid($parseresult['user_id']);



			if(count($territoryids) > 0)
			{
				foreach($territoryids as $territory_id)
				{
					$newsarray = $this->Mobile_model->get_lastnews($territory_id['parent_id']);

					if(count($newsarray) == 0)
					{
						while(true)
						{
							$ceklis = $this->Mobile_model->get_parentidbyter($territory_id['parent_id']);

							if(count($ceklis) == 0)
							{
								$berita = "";
								break;
							}
							else
							{
								$newsarray2 = $this->Mobile_model->get_lastnews($ceklis[0]['parent_id']);
								if(count($newsarray2) > 0)
								{
									$berita = $newsarray2[0]['news_content'];
									break;
								}else{
									$berita="";
									break;
								}
							}

						}

					}
					else
						$berita = $newsarray[0]['news_content'];
				}
			}
			
			
			
			$listevent = $this->Mobile_model->get_sellevent();
		
			if(count($listevent) > 0)
			{
				$ixx = 0;
				foreach($listevent as $dataevent)
				{
					$listarrayevent[$ixx] = array("sell_event_id" => $dataevent['sell_event_id'], "sell_event_name" => $dataevent['sell_event_name']);
					$ixx++;
				}
			}

			$vcombobisnis = $this->Mobile_model->get_vcombobusinessfocus();
		
			if(count($vcombobisnis) > 0)
			{
				$ixx = 0;
				foreach($vcombobisnis as $datacombo)
				{
					$listarraycombo[$ixx] = array("business_focus_value" => $datacombo['member_value'], "business_focus_name" => $datacombo['member_display']);
					$ixx++;
				}
			}
			
			$vcomboagentselling = $this->Mobile_model->get_vcomboagentsellingtype();
		
			if(count($vcomboagentselling) > 0)
			{
				$ixx = 0;
				foreach($vcomboagentselling as $datacombo)
				{
					$listarrayselling[$ixx] = array("agent_selling_value" => $datacombo['member_value'], "agent_selling_name" => $datacombo['member_display']);
					$ixx++;
				}
			}
			
			$vcomboclaim = $this->Mobile_model->get_vcomboclaimprogam();
		
			if(count($vcomboclaim) > 0)
			{
				$ixx = 0;
				foreach($vcomboclaim as $dataclaim)
				{
					$listarrayclaim[$ixx] = array("claim_value" => $dataclaim['mvalue'], "claim_name" => $dataclaim['mdisplay']);
					$ixx++;
				}
			}

			$vcomboagenttype = $this->Mobile_model->get_vcomboagenttype();
		
			if(count($vcomboagenttype) > 0)
			{
				$ixx = 0;
				foreach($vcomboagenttype as $dataagenttype)
				{
					$listarrayagenttype[$ixx] = array("agent_type_value" => $dataagenttype['member_value'], "agent_type_name" => $dataagenttype['member_display']);
					$ixx++;
				}
			}
			
				if($hasilarray[0]['user_group_id'] == 9)
			$programho = $this->Mobile_model->get_programho(2);
			else
			$programho = $this->Mobile_model->get_programho(1);
		
			if(count($programho) > 0)
			{
				$ixx = 0;
				foreach($programho as $dataho)
				{
					$listarrayho[$ixx] = array("ho_value" => $dataho['mvalue'], "ho_name" => $dataho['mdisplay']);
					$ixx++;
				}
			}
			
			if($hasilarray[0]['user_group_id'] == 9)
			$programcluster = $this->Mobile_model->get_programcluster($hasilarray[0]['user_id'],2);
			else
			$programcluster = $this->Mobile_model->get_programcluster($hasilarray[0]['user_id'],1);
			
            
            
            

                
                
			
			if($programcluster!=null && count($programcluster) > 0)
			{
				$ixx = 0;
				foreach($programcluster as $datacluster)
				{
					$listarraycluster[$ixx] = array("cluster_value" => $datacluster['mvalue'], "cluster_name" => $datacluster['mdisplay']);
					$ixx++;
				}
			}
			
			if($hasilarray[0]['user_group_id'] == 9)
			$programhouser = $this->Mobile_model->get_programho(4);
			else
			$programhouser = $this->Mobile_model->get_programho(3);
		      
		
			if(count($programhouser) > 0)
			{
				$ixx = 0;
				foreach($programhouser as $datahouser)
				{
					$listarrayhouser[$ixx] = array("ho_value" => $datahouser['mvalue'], "ho_name" => $datahouser['mdisplay']);
					$ixx++;
				}
			}
			
			if($hasilarray[0]['user_group_id'] == 9)
			$programclusteruser = $this->Mobile_model->get_programcluster($hasilarray[0]['user_id'],4);
			else
			$programclusteruser = $this->Mobile_model->get_programcluster($hasilarray[0]['user_id'],3);
			
			
			if($programclusteruser!=null && count($programclusteruser) > 0)
			{
				$ixx = 0;
				foreach($programclusteruser as $dataclusteruser)
				{
					$listarrayclusteruser[$ixx] = array("cluster_value" => $dataclusteruser['mvalue'], "cluster_name" => $dataclusteruser['mdisplay']);
					$ixx++;
				}
			}
			
			$user_group_id = $this->Mobile_model->get_groupid($parseresult['user_id']);

			if(count($user_group_id) > 0)
			{
				foreach($user_group_id as $usergroupid)
				{
					$usergroupid1 = $usergroupid['user_group_id'];
				}

			}
			
            
            


            
            
            
            
			//top
			$is_use_top = $this->Mobile_model->is_use_top($hasilarray[0]['user_group_id']);

			if($is_use_top==1)
			{
				$toplist = $this->Mobile_model->get_top();
			
			
				if(count($toplist) > 0)
				{
				$ixx = 0;
				foreach($toplist as $top)
				{
					$listarraytop[$ixx] = array("top_id" => $top['top_id'], "top_name" => $top['top_name']);
					$ixx++;
				}
				}
			}
			
			$termlist = $this->Mobile_model->get_term_konsinyasi();
			
			
				if(count($termlist) > 0)
				{
				$ixx = 0;
				foreach($termlist as $term)
				{
					$listarrayterm[$ixx] = array("term_id" => $term['term_id'], "term_name" => $term['term_name']);
					$ixx++;
				}
				}
                
                        
                
      
                
                
                
				
			$kpi = "";
			$kpis = $this->Mobile_model->get_kpi($parseresult['user_id']); 
                
			if(count($kpis) > 0)
			{
				foreach($kpis as $kpiku)
				{
					$kpi = $kpiku['f_get_kpi_by_userid'];
				}
			}

			$trackint = "";

			$trackints = $this->Mobile_model->get_trackint();

			if(count($trackints) > 0)
				$trackint = $trackints[0]['lookup_value'];
				
			$itemgroup = $this->Mobile_model->get_itemgroup();
			
			$ins = 0;
			foreach($itemgroup as $igroup)
			{
				$listarrayitemgroup[$ins] = array("item_group_id" => $igroup['item_group_name'], "item_group_name" => $igroup['item_group_name']);
				$ins++;
			}
			
			$setday=$this->Mobile_model->get_setday($parseresult['user_id']);
			     //Edited by RAA : dont need to check table	
				//if($hasilarray[0]['user_group_id'] == "31" or $hasilarray[0]['user_group_id'] == "9" or $hasilarray[0]['user_group_id'] == "8" ){
					//if ($hasilarray[0]['user_group_id']<>"5")
                    $listjourney = $this->Mobile_model->get_journeytoday_by_group($hasilarray[0]['user_group_id'],$parseresult['user_id']);
 
                //}
                
                

                
                
			$listarrayjourney=null;
			$listarrayjourney = array();
			if(isset($listjourney))
			if(count($listjourney) > 0)
			{
				$iww = 0;
				foreach($listjourney as $datajourney)
				{
					//if($this->helpme->startsWithChar($datajourney['channel_id'],'I')) //agent INX
				
				//	if($usergroupid1==31)
				//	{
					$datajourney['channel_id']=$this->Mobile_model->get_channel_id_by_territory_id($datajourney['territory_id']);
						$agents = $this->Mobile_model->get_agent($datajourney['channel_id']);
						if(count($agents) > 0){
						foreach($agents as $agent1)
						{
							$territory_type = $this->Mobile_model->get_territory_type($datajourney['territory_id']);
							$listarrayjourney[$iww] = array("jc_id" => $datajourney['jc_id'], "territory_type" => $territory_type, "channel_id" => $datajourney['channel_id'], "channel_name" => $agent1['agent_name'], "channel_address" => $agent1['agent_address'], "longitude" => $agent1['lon'], "latitude" => $agent1['lat'], "route_date" => $datajourney['tglku'],"sgo"=>'0');
						}
						}else{
						
							$outlets = $this->Mobile_model->get_outlet($datajourney['channel_id']);
							if(count($outlets) > 0)
							foreach($outlets as $outlet1)
							{
								$territory_type = $this->Mobile_model->get_territory_type($datajourney['territory_id']);
								$listarrayjourney[$iww] = array("jc_id" => $datajourney['jc_id'], "territory_type" => $territory_type, "channel_id" => $datajourney['channel_id'], "channel_name" => $outlet1['outlet_name'], "channel_address" => $outlet1['address'], "longitude" => $outlet1['lon'], "latitude" => $outlet1['lat'], "route_date" => $datajourney['tglku'],"sgo"=>$outlet1['sgo']);
							}
						}
					
				//	}
				/*	else if($usergroupid1==9)
					{
						$agents = $this->Mobile_model->get_agent($datajourney['channel_id']);
						if(count($agents) > 0)
						foreach($agents as $agent1)
						{
							$territory_type = $this->Mobile_model->get_territory_type($agent1['territory_id']);
							$listarrayjourney[$iww] = array("jc_id" => $datajourney['jc_id'], "territory_type" => $territory_type, "channel_id" => $datajourney['channel_id'], "channel_name" => $agent1['agent_name'], "channel_address" => $agent1['agent_address'], "longitude" => $agent1['lon'], "latitude" => $agent1['lat'], "route_date" => $datajourney['tglku']);
						}
					
					}
					else
					{
					//if($this->helpme->startsWithChar($datajourney['channel_id'],'C')) //outlet CJC
						$outlets = $this->Mobile_model->get_outlet($datajourney['channel_id']);
						if(count($outlets) > 0)
						foreach($outlets as $outlet1)
						{
							$territory_type = $this->Mobile_model->get_territory_type($outlet1['territory_id']);
							$listarrayjourney[$iww] = array("jc_id" => $datajourney['jc_id'], "territory_type" => $territory_type, "channel_id" => $datajourney['channel_id'], "channel_name" => $outlet1['outlet_name'], "channel_address" => $outlet1['address'], "longitude" => $outlet1['lon'], "latitude" => $outlet1['lat'], "route_date" => $datajourney['tglku']);
						}
					}*/
					$iww++;
				}
			}
		}
        
        
        
        			$vcomboalasan = $this->Mobile_model->get_vcomboalasanjc();
		
			if(count($vcomboalasan) > 0)
			{
				$ixxalasan = 0;
				foreach($vcomboalasan as $dataalasan)
				{
					$listarrayalasan[$ixxalasan] = array("lookup_value" => $dataalasan['lookup_value'], "lookup_desc" => $dataalasan['lookup_desc']);
					$ixxalasan++;
				}
			}
        
        
        

        $accesss='';
        $accesss=$this->Mobile_model->getaccess($usergroupid1);
        
        $access=array();
        if (count($accesss)>0){
            foreach ($accesss as $asdf){
            $access["$asdf[lookup]"]=$asdf['status'];       
    		}
        }
        //if($usergroupid1=="7"){$usergroupid1="5";} //absen only user grup hrus 5
        
   		//if($usergroupid1=="14"){$usergroupid1="4";} //dstl
        
        
		$result = array("success" => "true", "form" => $tablelist, "is_use_top" => $is_use_top, "top" => $listarraytop,"term_konsinyasi" => $listarrayterm, "user_id" => $parseresult['user_id'], "news" => $berita, "keyword" => $keyword, "server_date" => date('Y-m-d'), "server_time" => date('H:i'), "journeys" => array_values($listarrayjourney), "sell_events" => $listarrayevent, "business_focus" => $listarraycombo, "agent_type" => $listarrayagenttype, "user_group_id" => $usergroupid1, "kpi" => $kpi, "track_interval" => $trackint,"program_ho_channel" => $listarrayho,"program_cluster_channel" => $listarraycluster,"program_ho_user" => $listarrayhouser,"program_cluster_user" => $listarrayclusteruser, "must_change_password" => $must_change_password, "min_password_len" => $min_password, "claim_program" => $listarrayclaim, "item_groups" => $listarrayitemgroup, "setday" => $setday, "agent_selling_type" => $listarrayselling,"alasan_jc"=>$listarrayalasan,"access"=>$access);
        if(isset($datajourney)){
            if(count($datajourney)>0){
    		  $this->mglobal->saveLog('mobile-userlogin','succeed',$this->input->post('username'),'mobile-android',$this->input->post('username'));
    		   $this->Mobile_model->updateLoginStatus($this->input->post('username'),1);
            } else{
    		  $this->mglobal->saveLog('mobile-userlogin','no schedule',$this->input->post('username'),'mobile-android',$this->input->post('username'));
    		}
        } else{
    	   $this->mglobal->saveLog('mobile-userlogin','no schedule',$this->input->post('username'),'mobile-android',$this->input->post('username'));
    	}
        
        echo json_encode($result);
		exit;
	}
	
    
    
    
    
    
    
    
    
    
	public function getdaftarjatuhtempo()
	{
		$this->load->model('Mobile_model');
		
		$data = file_get_contents("php://input");

		$dataray = json_decode($data,TRUE);

		if(count($dataray) == 0)
		{
			$result = array("success" => "false", "error_code" => "100", "message" => "json format send failed");
			echo json_encode($result);
			exit;
		}

		$hasilkeyword = $this->Mobile_model->get_keywordtoday($dataray['user_id'],$dataray['keyword']);

		if(count($hasilkeyword) == 0)
		{
			$result = array("success" => "false", "error_code" => "200", "message" => "keyword failed", "user_id" => $dataray['user_id']);
			echo json_encode($result);
			exit;
		}
		$user_group_id = $this->Mobile_model->get_groupid($dataray['user_id']);
		
		$listarray=array();
		if($user_group_id==9)
		$listdata = $this->Mobile_model->get_jatuhtempo_agent($dataray['user_id']);
		else
		$listdata = $this->Mobile_model->get_jatuhtempo_outlet($dataray['user_id']);
		
			if(count($listdata) > 0)
			{
				$iww = 0;
				foreach($listdata as $data)
				{
					$listarray[$iww]=array("sell_in_id" => $data['sell_in_id'], "channel_id" => $data['channel_id'], "channel_name" => $data['channel_name'], "sell_in_date" => $data['sell_in_date']);
					$iww++;
				}
			}
			
			$result = array("success" => "true", "listdata" => $listarray);
			echo json_encode($result);
			exit;
		
		

	}
	
	public function getsellinitem() 
	{
		$this->load->model('Mobile_model');
		
		
		$data = file_get_contents("php://input");

		$dataray = json_decode($data,TRUE);

		$sellinid=$dataray['sell_in_id'];
		$userid=$dataray['user_id'];

		
		if(count($dataray) == 0)
		{
			$result = array("success" => "false", "error_code" => "100", "message" => "json format send failed");
			echo json_encode($result);
			exit;
		}
		
				$hasilkeyword = $this->Mobile_model->get_keywordtoday($dataray['user_id'],$dataray['keyword']);

		if(count($hasilkeyword) == 0)
		{
			$result = array("success" => "false", "error_code" => "200", "message" => "keyword failed", "user_id" => $dataray['user_id']);
			echo json_encode($result);
			exit;
		}

		
		$detailarray = $this->Mobile_model->get_sell_in_detail($sellinid,$userid);
		if(is_null($detailarray))
		{
			$result = array("success" => "false", "error_code" => "100", "message" => "Data is empty");
			echo json_encode($result);
		}
		else
		{
			$result['success'] = "true";
			$ins = 0;
			
			$listitem = $this->Mobile_model->get_sell_in_item($sellinid);
			foreach($listitem as $items)
			{
			$hasilarray = $this->Mobile_model->get_itemdetail($items['iccid']);
				foreach($hasilarray as $perbaris)
				{
				$hargaitem = $this->Mobile_model->get_price($perbaris['iccid'],$userid);
				$groupid = $this->Mobile_model->get_itemgroupbyiccid($perbaris['iccid']);
				$result['items'][$ins] = array("item_id" => $perbaris['item_id'], "item_name" => $perbaris['item_name'], "item_code" => $perbaris['iccid'], "price" => $hargaitem, "item_group_id" => $groupid);
				$ins++;
				}
			}
			$result['jumlah'] = $detailarray[0]['juml'];
			$result['tagihan'] = $detailarray[0]['tagihan'];
			
			echo json_encode($result);
		}
	}
	
	public function addkonsinyasititip()
	{
		$this->load->model('Mobile_model');
		$data = file_get_contents("php://input");
		$dataray = json_decode($data,TRUE);

		if(count($dataray) == 0) {
			$result = array("success" => "false", "error_code" => "100", "message" => "json format send failed");
			echo json_encode($result);
			exit;
		}

		$keyword = $this->Mobile_model->get_keywordtoday($dataray['user_id'], $dataray['keyword']);
		if(count($keyword) == 0) {
			$result = array("success" => "false", "error_code" => "200", "message" => "Keyword Gagal", "user_id" => $dataray['user_id']);
			echo json_encode($result);
			exit;
		}

		if ($dataray['channel_id'] == '' OR is_null($dataray['channel_id'])) {   
			$result = array("success" => "false", "error_code" => "300", "message" => "Partner Id Tidak Terbaca", "user_id" => $dataray['user_id']);
			echo json_encode($result);
			exit;
		}

		$validated_iccid = $this->Mobile_model->ValidateItem($dataray["items"]);
		if(count($validated_iccid['invalid']) != 0 && count($validated_iccid['valid']) != 0 ) {
			$invalid_iccid = "\n\r";
			foreach ($validated_iccid['invalid'] as $key) 
				{ $invalid_iccid .= $key.", "; }
			$invalid_iccid = substr($invalid_iccid, 0, -6); 
			$result = array("success" => "false", "error_code" => "100", "message" => "ICCID tidak valid: $invalid_iccid ", "user_id" => $dataray['user_id']);
		}
		if(count($validated_iccid['valid']) == 0) {
			$result = array("success" => "false", "error_code" => "100", "message" => "Semua item tidak sudah pernah dijual atau konsinyasi", "user_id" => $dataray['user_id']);
			echo json_encode($result);
		}
		else {
			$this->db->trans_begin();

			$trx_id = $this->Mobile_model->add_konsinyasi($dataray);
			if(count($dataray['program_ho']) == 0 )
				{ $program_id[] = 1; }
			else
				{ $program_id[] = $dataray['program_ho'][0]; }
			
			if($program_id[0] == 'null' OR $program_id[0] == '' )
				{ $program_id[0] = '1'; }
			if($dataray['program_cluster'])
				{ $program_id[] = $dataray['program_cluster'][0]; }
			foreach($program_id as $program)
				{ $this->Mobile_model->add_konsinyasi_program($trx_id, $program, $dataray['user_id']); }
			foreach ($validated_iccid['valid'] as $item) 
				{ $this->Mobile_model->add_konsinyasi_detail($item, $trx_id, $dataray['user_id']); }
			
			$db_sri = $this->load->database('Retails', TRUE);
			$db_sri->trans_begin();
			// $this->load->model('mintegrasi');
			// $this->mintegrasi->StockIn($dataray["channel_id"], $validated_iccid['valid'], $trx_id, 'consignment', $dataray['user_id']);

			$this->load->model('mintegrasi');
			$this->mintegrasi->StockIn($dataray["channel_id"], $validated_iccid['valid'], $trx_id, 'consignment', $dataray['user_id']);

			$log = array('consignment_id' => $trx_id, 'program_id' => $program_id, 'ICCID' => $validated_iccid['valid'] );
			$this->mglobal->saveLog('consignment', 'create; id='.json_encode($log), $dataray['user_id'], 'mobile-android' );

      if ($this->db->trans_status() === FALSE OR $db_sri->trans_status() === FALSE) { 
        $this->db->trans_rollback();
        $db_sri->trans_rollback();
        $result = array("success" => "false", "error_code" => "100", "message" => "Transaksi gagal", "user_id" => $dataray['user_id']);
        echo json_encode($result);
			}
			else { 
        $this->db->trans_commit();
        $db_sri->trans_commit();
        $result = array("success" => "true", "message" => "Transaksi sukses", "user_id" => $dataray['user_id']);
        echo json_encode($result);
			}
		}

	} // end of addkonsinyasititip()
	
	public function getkonsinyasi() 
	{
		$this->load->model('Mobile_model');
		
		
		$data = file_get_contents("php://input");

		$dataray = json_decode($data,TRUE);

		

		
		if(count($dataray) == 0)
		{
			$result = array("success" => "false", "error_code" => "100", "message" => "json format send failed");
			echo json_encode($result);
			exit;
		}
		
				$hasilkeyword = $this->Mobile_model->get_keywordtoday($dataray['user_id'],$dataray['keyword']);

		if(count($hasilkeyword) == 0)
		{
			$result = array("success" => "false", "error_code" => "200", "message" => "keyword failed", "user_id" => $dataray['user_id']);
			echo json_encode($result);
			exit;
		}

		$terrid=$this->Mobile_model->get_territory($dataray['channel_id']);
		$hasilarray = $this->Mobile_model->get_konsinyasi($terrid);
		if(is_null($hasilarray))
		{
			$result = array("success" => "false", "error_code" => "100", "message" => "Data is empty");
			echo json_encode($result);
		}
		else
		{
			$result['success'] = "true";
			$ins = 0;
			
				foreach($hasilarray as $perbaris)
				{
				
				$result['konsinyasi'][$ins] = $perbaris['consignment_id'];
				$ins++;
				}
			
			
			
			echo json_encode($result);
		}
	}
	
	public function getitemkonsinyasi() 
	{
		$this->load->model('Mobile_model');
		
		
		$data = file_get_contents("php://input");

		$dataray = json_decode($data,TRUE);

		

		
		if(count($dataray) == 0)
		{
			$result = array("success" => "false", "error_code" => "100", "message" => "json format send failed");
			echo json_encode($result);
			exit;
		}
		
				$hasilkeyword = $this->Mobile_model->get_keywordtoday($dataray['user_id'],$dataray['keyword']);

		if(count($hasilkeyword) == 0)
		{
			$result = array("success" => "false", "error_code" => "200", "message" => "keyword failed", "user_id" => $dataray['user_id']);
			echo json_encode($result);
			exit;
		}

		$hasilarray=$this->Mobile_model->get_item_konsinyasi($dataray['consignment_id']);
		
		if(is_null($hasilarray))
		{
			$result = array("success" => "false", "error_code" => "100", "message" => "Data is empty");
			echo json_encode($result);
		}
		else
		{
			$result['success'] = "true";
			$ins = 0;
			
				foreach($hasilarray as $perbaris)
				{
				
				$query = $this->Mobile_model->get_itemdetail($perbaris['iccid']);
							
							$hargaitem = $perbaris['price'];
							
							
							foreach($query as $hasilperbaris)
							{
								$groupid = $this->Mobile_model->get_itemgroupbyiccid($perbaris['iccid']);
								$result['items'][$ins] = array("item_id" => $hasilperbaris['item_id'], "item_name" => $hasilperbaris['item_name'], "item_code" => $hasilperbaris['iccid'], "price" => $hargaitem, "item_group_id" => $groupid);
								
								$ins++;
									
							}
								
					
							
				
				}
			
			
			
			echo json_encode($result);
		}
	}
	
	public function updatekonsinyasi()
	{
		$this->load->model('Mobile_model');
		$this->load->model('mconsignment');

		$data = file_get_contents("php://input");
		$dataray = json_decode($data,TRUE);

		if(count($dataray) == 0) {
			$result = array("success" => "false", "error_code" => "100", "message" => "json format send failed");
			echo json_encode($result);
			exit;
		}

		$hasilkeyword = $this->Mobile_model->get_keywordtoday($dataray['user_id'],$dataray['keyword']);
		if(count($hasilkeyword) == 0) {
			$result = array("success" => "false", "error_code" => "200", "message" => "keyword failed", "user_id" => $dataray['user_id']);
			echo json_encode($result);
			exit;
		}

		$this->db->trans_begin();

			$this->Mobile_model->update_konsinyasi($dataray['consignment_id'], 2);
			if(count($dataray["items"]) > 0 ) {
				$newSellIn = $this->mconsignment->createSellIn($dataray['consignment_id'], 'mobile-android'); //masukin ke sellin
				$this->mconsignment->sellInDetail($newSellIn, $dataray["items"], $dataray['consignment_id']);
			}
			else 
				{ $this->Mobile_model->normalize_consignment($dataray['consignment_id'], $dataray["items"]); }

			$this->mglobal->saveLog('consignment',"takeout: ".json_encode($dataray), $dataray['user_id'], 'mobile-android', $dataray['user_id']);
		if ($this->db->trans_status() === FALSE) { 
		  $this->db->trans_rollback(); 
		  return false;
		}
		else { 
		  $this->db->trans_commit(); 
			$result = array("success" => "true",  "message" => "Data berhasil disimpan\nTotal barang terjual : ". count($dataray['items']) , "user_id" => $dataray['user_id']);
			echo json_encode($result);
		}


	} // end of updatekonsinyasi
	
	
	public function getnotifikasi() 
	{
		$this->load->model('Mobile_model');
		
		
		$data = file_get_contents("php://input");

		$dataray = json_decode($data,TRUE);

		

		
		if(count($dataray) == 0)
		{
			$result = array("success" => "false", "error_code" => "100", "message" => "json format send failed");
			echo json_encode($result);
			exit;
		}
		
				$hasilkeyword = $this->Mobile_model->get_keywordtoday($dataray['user_id'],$dataray['keyword']);

		if(count($hasilkeyword) == 0)
		{
			$result = array("success" => "false", "error_code" => "200", "message" => "keyword failed", "user_id" => $dataray['user_id']);
			echo json_encode($result);
			exit;
		}

		$hasilarray=$this->Mobile_model->get_msg($dataray['user_id']);
		
		if(is_null($hasilarray))
		{
			$result = array("success" => "false", "error_code" => "100", "message" => "Data is empty");
			echo json_encode($result);
		}
		else
		{
			$result['success'] = "true";
			$ins = 0;
			
				foreach($hasilarray as $perbaris)
				{
				
				
								$result['messages'][$ins] = array("msg_id" => $perbaris['msg_id'], "msg_subject" => $perbaris['msg_subject'], "msg_body" => $perbaris['msg_body']);
								
								$ins++;
									
							
								
					
							
				
				}
			
			
			
			echo json_encode($result);
		}
	}
	
	public function syncScanIn()
	{
		$this->load->model('Mobile_model');

		$data = file_get_contents("php://input");
		
		$dataray = json_decode($data,TRUE);

		if(count($dataray) == 0)
		{
			$result = array("success" => "false", "error_code" => "100", "message" => "json format send failed");
			echo json_encode($result);
			exit;
		}

		$hasilkeyword = $this->Mobile_model->get_keywordtoday($dataray['user_id'],$dataray['keyword']);

		if(count($hasilkeyword) == 0)
		{
			$result = array("success" => "false", "error_code" => "200", "message" => "keyword failed", "user_id" => $dataray['user_id']);
			echo json_encode($result);
			exit;
		}

		foreach($hasilkeyword as $clients)
			$client = $clients['client'];

		$matchs = array();
		$intcek = 0;
		
		$barangok = 0;
			$barangbad = 0;
			$valid_item = array();
			$failed_item = array();
			$failed_item_message = array();
			$good_item = array();
			
		
		
		
		  $dn='';
            //$dd=array();

			$hasilarray = $this->Mobile_model->get_scan_in_items($dataray['user_id']);
			if(count($hasilarray) > 0){
			     foreach($hasilarray as $perbaris)
                 $dd[]=$perbaris['iccid'];        
                 
                            $arrayhasil=array_diff($dd,$dataray['items']);
							/*
                            foreach($hasilarray as $perbaris)
							{
							    $aa=array_search($perbaris['iccid'],$dataray['items']);
                                //$dn.=$aa.'|';
                                $found='f';
                                foreach($dataray['items'] as $dti){
                                    if($perbaris['iccid']==$dti){
                                    $found=$perbaris['iccid'].'t'.$dti;
                                    }
                                }
                                $dn.=$found.'|';
                            
    							if(in_array($perbaris['iccid'],$dataray['items'])==''){

    							}
							}*/
                            foreach($arrayhasil as $asdfg){
		                        
                                $query = $this->Mobile_model->get_itemdetail($asdfg);
    							
                                
    							$hargaitem = $this->Mobile_model->get_price($asdfg,$dataray['user_id']);
    							
        							if(count($query) > 0)
        							foreach($query as $hasilperbaris)
        							{
        								$groupid = $this->Mobile_model->get_itemgroupbyiccid($hasilperbaris['iccid']);
        								
        								$valid_item[$barangok] = array("item_id" => $hasilperbaris['item_id'], "item_name" => $hasilperbaris['item_name'], "item_code" => $hasilperbaris['iccid'], "price" => $hargaitem, "item_group_id" => $groupid);
        								$barangok++;
        								
        								
        					
        							}
                                    
                            }
                            
           // $result = array("success" => "false", "error_code" => "100", "message" => "r: ".$dn.'__'.count($valid_item).'__'.count($hasilarray).'__'.count($dataray['items']));
		//	echo json_encode($result);
		//	exit;	

		
			
				
				
					$result = array("success" => "true", "user_id" => $dataray['user_id'], "valid_items" => $valid_item);
					echo json_encode($result);
					exit;
				}else{
				$result = array("success" => "false", "error_code" => "100", "message" => "Tidak ada yang perlu di sinkronisasi");
			echo json_encode($result);
			exit;
				}
			
		

	}
	
	public function addsgsIn()
	{
		$this->load->model('Mobile_model');

		$data = file_get_contents("php://input");
		
		$dataray = json_decode($data,TRUE);

		if(count($dataray) == 0)
		{
			$result = array("success" => "false", "error_code" => "100", "message" => "json format send failed");
			echo json_encode($result);
			exit;
		}

		$hasilkeyword = $this->Mobile_model->get_keywordtoday($dataray['user_id'],$dataray['keyword']);

		if(count($hasilkeyword) == 0)
		{
			$result = array("success" => "false", "error_code" => "200", "message" => "keyword failed", "user_id" => $dataray['user_id']);
			echo json_encode($result);
			exit;
		}

		foreach($hasilkeyword as $clients)
			$client = $clients['client'];

		$matchs = array();
		$intcek = 0;
		
		$barangok = 0;
			$barangbad = 0;
			$valid_item = array();
			$failed_item = array();
			$failed_item_message = array();
			$good_item = array();
			
		
		
		if(count($dataray['items']) > 0)
		{	foreach($dataray['items'] as $dataitem)
			{
				//$matchs[$intcek] = array("true" => "valid", "value" => $dataitem);
				//$intcek++;
				$valid = "0";
				$valid = $this->Mobile_model->check_valid_item_in_store($dataitem,$dataray['channel_id'],$dataray['user_id']);
			
				//if(count($valids) > 0)
				//{
					//foreach($valids as $validku)
					//{
						//$valid = $validku['f_check_valid_item'];
						
						if($valid=="OK")
						{
							$query = $this->Mobile_model->get_itemdetail($dataitem);
							
							$hargaitem = $this->Mobile_model->get_price($dataitem,$dataray['user_id']);
							
							
							
							
							if(count($query) > 0)
							foreach($query as $hasilperbaris)
							{
								$groupid = $this->Mobile_model->get_itemgroupbyiccid($dataitem);
								$good_item[$barangok] = $dataitem;
								$valid_item[$barangok] = array("item_id" => $hasilperbaris['item_id'], "item_name" => $hasilperbaris['item_name'], "item_code" => $hasilperbaris['iccid'], "price" => $hargaitem, "item_group_id" => $groupid);
								$barangok++;
								
								
					
							}
							
						$valid="0";
						}else{
						
							$failed_item_message[$barangbad] = $valid;
							$failed_item[$barangbad] = $dataitem;
							$barangbad++;
						}
					//}
				//}*/
				
			}
			
			if($barangbad == count($dataray['items']))
			{
				$result = array("success" => "false", "error_code" => "300", "message" => "Semua item tidak valid", "failed_items" => $failed_item, "failed_items_msg" => $failed_item_message , "user_id" => $dataray['user_id']);
				echo json_encode($result);
				exit;
			}
			else
			{
				
				
				if($barangok == count($dataray['items']))
				{
					$result = array("success" => "true", "user_id" => $dataray['user_id'], "failed_items" => $failed_item, "failed_items_msg" => $failed_item_message, "valid_items" => $valid_item);
					echo json_encode($result);
					exit;
				}
				else
				{
					$result = array("success" => "true", "error_code" => "300", "message" => "Beberapa item tidak valid", "failed_items" => $failed_item, "failed_items_msg" => $failed_item_message, "user_id" => $dataray['user_id'], "valid_items" => $valid_item);
					echo json_encode($result);
					exit;
				}
			}
		}

	}
	
	public function addsellout()
	{
		$this->load->model('Mobile_model');

		$data = file_get_contents("php://input");
		
		$dataray = json_decode($data,TRUE);
		
		if(count($dataray) == 0)
		{
			$result = array("success" => "false", "error_code" => "100", "message" => "json format send failed");
			echo json_encode($result);
			exit;
		}

		$hasilkeyword = $this->Mobile_model->get_keywordtoday($dataray['user_id'],$dataray['keyword']);

		if(count($hasilkeyword) == 0)
		{
			$result = array("success" => "false", "error_code" => "200", "message" => "keyword failed", "user_id" => $dataray['user_id']);
			echo json_encode($result);
			exit;
		}

		foreach($hasilkeyword as $clients)
			$client = $clients['client'];
		
		$matchs = array();
		$intcek = 0;
		
		$barangok = 0;
			$barangbad = 0;
			$failed_item = array();
			$good_item = array();
			
		if(count($dataray['items']) > 0)
		{
			
			$terrid = $this->Mobile_model->get_territory($dataray['channel_id']);
			//-----------------------start
				$this->db->trans_begin();
				//-----------------------begin process
			$sellid = $this->Mobile_model->add_sellout($dataray,$terrid);
			$this->mglobal->saveLog('add-sellout-header',"added:".json_encode($dataray),$dataray['user_id'],'mobile-android',$dataray['user_id']);
			
		foreach($dataray['items'] as $dataitem)
			{						
							$this->Mobile_model->add_sellout_detail($dataitem,$sellid,$dataray);
			}
			//-----------------------end process
				if ($this->db->trans_status() === FALSE)
				{
					$this->db->trans_rollback();
				}
				else
				{
					$this->db->trans_commit();
                    
				}
				//-----------------------end
			$result = array("success" => "true", "user_id" => $dataray['user_id']);
			echo json_encode($result);
			exit;
		}else{
		$result = array("success" => "false", "error_code" => "300", "message" => "Item is empty", "user_id" => $dataray['user_id']);
				echo json_encode($result);
				exit;
		}

	}
    
    public function test(){
        echo 'OK';
        exit;
    }
    public function absent($lon, $lat,$acc,$uid){
        $this->load->model('Mobile_model');
        $add=$this->Mobile_model->add_absent($lon, $lat,$acc,$uid);
        $this->mglobal->saveLog('add-absent',"added:".json_encode(array($lon, $lat,$acc,$uid)),$uid,'mobile-android',$uid);
        if($add){
  		$result = array("success" => "true", "user_id" => $uid);
		echo json_encode($result);
		exit;
        }else{
		$result = array("success" => "false","error_code" => "300", "message" => "Item is empty", "user_id" => $uid);
		echo json_encode($result);
		exit;
        }
    }

}

/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */
/* Because  sublimetext is too mainstream*/